Exemplo n.º 1
0
    def __init__(self):
        super(PollingThread, self).__init__()

        self.expires = 0
        self.last_refresh = time.time()
        self.player = MyPlayer()
        self.shared_data = SharedData()
Exemplo n.º 2
0
    def __init__(self, conn_string):
        super(Prompt, self).__init__()

        # Build database connection
        self.conn = psycopg2.connect(conn_string)
        self.cur = self.conn.cursor(
            cursor_factory=psycopg2.extras.DictCursor
        )  #create database cursor. parameter grabs result as dict (which is not default)
        self.conn.autocommit = True  #disable transactions (transactions left uncommitted will hang the game)

        self.myplayer = MyPlayer(self.cur)
        self.game = Game(self.cur)
        self.armada = Armada(self.cur)
Exemplo n.º 3
0
class PollingThread(BaseThread):

    def __init__(self):
        super(PollingThread, self).__init__()

        self.expires = 0
        self.last_refresh = time.time()
        self.player = MyPlayer()
        self.shared_data = SharedData()

    def refreshLiveUrl(self):
        if self.shared_data.get('playing.what') == 'nba_tv_live':
            video_url = TV.get_live_url(force_login=True)
        elif self.shared_data.get('playing.what') == 'nba_tv_episode':
            start_timestamp = self.shared_data.get('playing.data.start_timestamp')
            duration = self.shared_data.get('playing.data.duration')
            video_url = TV.get_episode_url(start_timestamp, duration, force_login=True)

        if video_url:
            self.readExpiresFromUrl(video_url)
            utils.log("Updating live url from service, new url (%s) and expire (%d)" 
                % (video_url, self.expires))

            self.player.play(video_url)

    def readExpiresFromUrl(self, url):
        url_parts = urlparse(url)

        #Parse query string to dictionary
        query_params = parse_qs(url_parts.query)

        #Get the hdnea param, where the "expires" param is
        hdnea_params = query_params.get("hdnea")[0]
        hdnea_params = hdnea_params.replace('~', '&')
        hdnea_params = urllib.unquote(hdnea_params)

        self.expires = parse_qs(hdnea_params).get("expires", 0)[0]
        self.expires = int(self.expires)

    def run(self):
        while True:
            try:
                current_playing_url = self.player.getPlayingFile()
                self.readExpiresFromUrl(current_playing_url)
                utils.log("Playing url: %s - playing cache: %s" % 
                    (current_playing_url, self.shared_data.get("playing")), xbmc.LOGDEBUG)
            except:
                pass

            if self.shared_data.get("playing.what"):
                #Wait second iteration before checking the expiration
                if self.shared_data.get("playing.second_iteration") != "1":
                    xbmc.sleep(2000);
                    self.shared_data.set("playing.second_iteration", "1")
                    continue;

                timestamp = time.time()

                #Avoid refreshing too fast, let at least one minute pass from the last refresh
                expire_timestamp = max(self.expires, self.last_refresh + 60)

                utils.log("%d seconds to url refresh" % (expire_timestamp - timestamp))
                if timestamp > expire_timestamp:
                    self.refreshLiveUrl()
                    self.last_refresh = timestamp

            xbmc.sleep(1000)

            if not self.should_keep_running():
                utils.log("Interrupting service loop")
                break 
Exemplo n.º 4
0
from board import Board, Direction, Rotation
from constants import BOARD_WIDTH, BOARD_HEIGHT, INTERVAL
from player import Player, SelectedPlayer, RandomPlayer, MyPlayer
from adversary import RandomAdversary


def run(seed, player):
    board = Board(BOARD_WIDTH, BOARD_HEIGHT)
    adversary = RandomAdversary(seed=seed)

    for move in board.run(player=player, adversary=adversary):
        pass

    return board.score


if __name__ == '__main__':
    index = 0
    signed = []
    weights = []
    for i in range(5):
        player = MyPlayer()

        print(run(42, RandomPlayer()))
Exemplo n.º 5
0
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.box = BoxHelper()
        self.box.update_thread.startThread.connect(self.startUpdate)
        self.box.update_thread.endThread.connect(self.endUpdate)
        
        self.db = MusicDB()
        self.query = QSqlQuery()
        self.player = MyPlayer()
        self.player.player.mediaStatusChanged.connect(self.qmp_mediaStatusChanged)
        self.player.player.stateChanged.connect(self.qmp_stateChanged)
        self.player.player.positionChanged.connect(self.qmp_positionChanged)
        self.player.player.volumeChanged.connect(self.qmp_volumeChanged)
        self.player.currentIndexChanged.connect(self.playlistIdxChanged)
        self.playlist = {}

        self.setFixedWidth(900)
        self.setFixedHeight(600)

        layout = QVBoxLayout()
        hlayout = QHBoxLayout()

        hlayout2 = QHBoxLayout()
        self.labelCover = QLabel()
        self.labelCover.setFixedWidth(200)
        self.labelCover.setFixedHeight(200)
        hlayout2.addWidget(self.labelCover)

        vlayout2 = QVBoxLayout()
        vlayout2.addStretch()
        self.labelTitle = QLabel()
        self.labelTitle.setWordWrap(True)
        vlayout2.addWidget(self.labelTitle)
        self.labelAlbum = QLabel()
        self.labelAlbum.setWordWrap(True)
        vlayout2.addWidget(self.labelAlbum)
        self.labelArtist = QLabel()
        self.labelArtist.setWordWrap(True)
        self.labelArtist.setFixedWidth(300)
        vlayout2.addWidget(self.labelArtist)
        vlayout2.addStretch()
        hlayout2.addLayout(vlayout2)

        controlArea = QVBoxLayout()  
        seekSliderLayout = QHBoxLayout()
        controls = QHBoxLayout()
        playlistCtrlLayout = QHBoxLayout()
        
        #creating buttons
        pixmap = QPixmap("pause-play-button.png")
        buttonIcon = QIcon(pixmap)
        self.pauseBtn = QPushButton()
        self.pauseBtn.setIcon(buttonIcon)
        self.pauseBtn.setIconSize(pixmap.rect().size())
        pixmap = QPixmap("stop-button.png")
        buttonIcon = QIcon(pixmap)
        self.stopBtn = QPushButton()
        self.stopBtn.setIcon(buttonIcon)
        self.stopBtn.setIconSize(pixmap.rect().size())
        pixmap = QPixmap("volumedown-button.png")
        buttonIcon = QIcon(pixmap)
        self.volumeDescBtn = QPushButton()
        self.volumeDescBtn.setIcon(buttonIcon)
        self.volumeDescBtn.setIconSize(pixmap.rect().size())
        pixmap = QPixmap("volumeup-button.png")
        buttonIcon = QIcon(pixmap)
        self.volumeIncBtn = QPushButton()
        self.volumeIncBtn.setIcon(buttonIcon)
        self.volumeIncBtn.setIconSize(pixmap.rect().size())

        self.progress = QProgressBar()
        self.progress.setRange(0, 100)
        self.progress.setTextVisible(True)
        self.progress.setValue(self.player.player.volume())
        
        #creating playlist controls
        pixmap = QPixmap("previous-track-button.png")
        buttonIcon = QIcon(pixmap)
        self.prevBtn = QPushButton()
        self.prevBtn.setIcon(buttonIcon)
        self.prevBtn.setIconSize(pixmap.rect().size())
        
        vlayout3 = QVBoxLayout()
        self.labelPlaylist = QLabel()
        self.labelPlaylist.setAlignment(Qt.AlignCenter)
        self.labelPlaylist.setText("No Songs")
        vlayout3.addWidget(self.labelPlaylist)
        pixmap = QPixmap("playlist-button.png")
        buttonIcon = QIcon(pixmap)
        self.playlistBtn = QPushButton()
        self.playlistBtn.setIcon(buttonIcon)
        self.playlistBtn.setIconSize(pixmap.rect().size())
        self.playlistBtn.setCheckable(True)
        vlayout3.addWidget(self.playlistBtn)
        pixmap = QPixmap("next-track-button.png")
        buttonIcon = QIcon(pixmap)
        self.nextBtn = QPushButton()
        self.nextBtn.setIcon(buttonIcon)
        self.nextBtn.setIconSize(pixmap.rect().size())

        #creating seek slider
        self.seekSlider = QSlider()
        self.seekSlider.setMinimum(0)
        self.seekSlider.setMaximum(100)
        self.seekSlider.setOrientation(Qt.Horizontal)
        self.seekSlider.setTracking(False)
        self.seekSlider.sliderMoved.connect(self.seekPosition)
        #self.seekSlider.valueChanged.connect(self.seekPosition)
        
        self.seekSliderLabel1 = QLabel('0.00')
        self.seekSliderLabel2 = QLabel('0.00')
        seekSliderLayout.addWidget(self.seekSliderLabel1)
        seekSliderLayout.addWidget(self.seekSlider)
        seekSliderLayout.addWidget(self.seekSliderLabel2)
        
        #Add handler for each button. Not using the default slots.
        self.pauseBtn.clicked.connect(self.play)
        self.stopBtn.clicked.connect(self.player.stopHandler)
        self.volumeDescBtn.clicked.connect(self.player.decreaseVolume)
        self.volumeIncBtn.clicked.connect(self.player.increaseVolume)
        
        #Adding to the horizontal layout
        controls.addWidget(self.volumeDescBtn)
        controls.addWidget(self.pauseBtn)
        controls.addWidget(self.stopBtn)
        controls.addWidget(self.volumeIncBtn)
        
        #playlist control button handlers
        self.prevBtn.clicked.connect(self.player.prevItemPlaylist)
        self.nextBtn.clicked.connect(self.player.nextItemPlaylist)
        self.playlistBtn.clicked.connect(self.showPlaylist)
        playlistCtrlLayout.addWidget(self.prevBtn)
        playlistCtrlLayout.addLayout(vlayout3)
        playlistCtrlLayout.addWidget(self.nextBtn)
        
        #Adding to the vertical layout
        controlArea.addLayout(seekSliderLayout)
        controlArea.addLayout(controls)
        controlArea.addWidget(self.progress)
        controlArea.addLayout(playlistCtrlLayout)
        hlayout2.addLayout(controlArea)
        layout.addLayout(hlayout2)

        self.stack = QStackedWidget()
        self.view = QTableView()
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.proxy = MyProxyModel()
        self.proxy.setSourceModel(self.db.model)
        self.view.setModel(self.proxy)
        self.view.hideColumn(0)
        self.view.hideColumn(4)
        self.view.hideColumn(5)
        self.view.hideColumn(6)
        self.view.hideColumn(7)
        self.view.hideColumn(9)
        self.view.hideColumn(10)
        self.view.hideColumn(11)
        self.view.selectionModel().selectionChanged.connect(self.viewSelection)
        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.contextMenuEvent)
        self.view.resizeColumnsToContents()
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.setSortingEnabled(True)
        self.view.verticalHeader().setVisible(False)
        self.stack.addWidget(self.view)
        self.viewpl = QListView()
        self.modelpl = QStandardItemModel()
        self.viewpl.setModel(self.modelpl)
        self.stack.addWidget(self.viewpl)
        layout.addWidget(self.stack)
        
        hlayout2 = QHBoxLayout()
        pixmap = QPixmap("search-button.png")
        buttonIcon = QIcon(pixmap)
        self.pushButton_2 = QPushButton()
        self.pushButton_2.setIcon(buttonIcon)
        self.pushButton_2.setIconSize(pixmap.rect().size())
        hlayout2.addWidget(self.pushButton_2)
        self.lineEdit = QLineEdit()
        hlayout2.addWidget(self.lineEdit)
        layout.addLayout(hlayout2)
#        
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
#
#        self.status = QStatusBar()
#        self.setStatusBar(self.status)
#
#        # Uncomment to disable native menubar on Mac
        self.menuBar().setNativeMenuBar(False)
#
#        file_toolbar = QToolBar("File")
#        file_toolbar.setIconSize(QSize(14, 14))
#        self.addToolBar(file_toolbar)
        file_menu = self.menuBar().addMenu("&File")

        add_file_action = QAction("Upload file...", self) #QIcon(os.path.join('images', 'blue-folder-open-document.png')), "Open file...", self)
        add_file_action.setStatusTip("Upload file")
        add_file_action.triggered.connect(self.addFile)
        file_menu.addAction(add_file_action)

        save_file_action = QAction("Remove file..", self)
        save_file_action.setStatusTip("Remove Selected File")
        save_file_action.triggered.connect(self.removeFile)
        file_menu.addAction(save_file_action)

#
#        saveas_file_action = QAction(QIcon(os.path.join('images', 'disk--pencil.png')), "Save As...", self)
#        saveas_file_action.setStatusTip("Save current page to specified file")
#        saveas_file_action.triggered.connect(self.file_saveas)
#        file_menu.addAction(saveas_file_action)
#        file_toolbar.addAction(saveas_file_action)
#
#        print_action = QAction(QIcon(os.path.join('images', 'printer.png')), "Print...", self)
#        print_action.setStatusTip("Print current page")
#        print_action.triggered.connect(self.file_print)
#        file_menu.addAction(print_action)
#        file_toolbar.addAction(print_action)
#
#        edit_toolbar = QToolBar("Edit")
#        edit_toolbar.setIconSize(QSize(16, 16))
#        self.addToolBar(edit_toolbar)
#        edit_menu = self.menuBar().addMenu("&Edit")
#
#        undo_action = QAction(QIcon(os.path.join('images', 'arrow-curve-180-left.png')), "Undo", self)
#        undo_action.setStatusTip("Undo last change")
#        undo_action.triggered.connect(self.editor.undo)
#        edit_menu.addAction(undo_action)
#
#        redo_action = QAction(QIcon(os.path.join('images', 'arrow-curve.png')), "Redo", self)
#        redo_action.setStatusTip("Redo last change")
#        redo_action.triggered.connect(self.editor.redo)
#        edit_toolbar.addAction(redo_action)
#        edit_menu.addAction(redo_action)
#
#        edit_menu.addSeparator()
#
#        cut_action = QAction(QIcon(os.path.join('images', 'scissors.png')), "Cut", self)
#        cut_action.setStatusTip("Cut selected text")
#        cut_action.setShortcut(QKeySequence.Cut)
#        cut_action.triggered.connect(self.editor.cut)
#        edit_toolbar.addAction(cut_action)
#        edit_menu.addAction(cut_action)
#
#        copy_action = QAction(QIcon(os.path.join('images', 'document-copy.png')), "Copy", self)
#        copy_action.setStatusTip("Copy selected text")
#        cut_action.setShortcut(QKeySequence.Copy)
#        copy_action.triggered.connect(self.editor.copy)
#        edit_toolbar.addAction(copy_action)
#        edit_menu.addAction(copy_action)
#
#        paste_action = QAction(QIcon(os.path.join('images', 'clipboard-paste-document-text.png')), "Paste", self)
#        paste_action.setStatusTip("Paste from clipboard")
#        cut_action.setShortcut(QKeySequence.Paste)
#        paste_action.triggered.connect(self.editor.paste)
#        edit_toolbar.addAction(paste_action)
#        edit_menu.addAction(paste_action)
#
#        select_action = QAction(QIcon(os.path.join('images', 'selection-input.png')), "Select all", self)
#        select_action.setStatusTip("Select all text")
#        cut_action.setShortcut(QKeySequence.SelectAll)
#        select_action.triggered.connect(self.editor.selectAll)
#        edit_menu.addAction(select_action)

        self.setWindowTitle("Music DB")
#        self.setWindowIcon(QIcon('stemma.png'))

        self.show()

        #self.pushButton.clicked.connect(self.play)
        self.pushButton_2.clicked.connect(self.searchSong)
Exemplo n.º 6
0
class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.box = BoxHelper()
        self.box.update_thread.startThread.connect(self.startUpdate)
        self.box.update_thread.endThread.connect(self.endUpdate)
        
        self.db = MusicDB()
        self.query = QSqlQuery()
        self.player = MyPlayer()
        self.player.player.mediaStatusChanged.connect(self.qmp_mediaStatusChanged)
        self.player.player.stateChanged.connect(self.qmp_stateChanged)
        self.player.player.positionChanged.connect(self.qmp_positionChanged)
        self.player.player.volumeChanged.connect(self.qmp_volumeChanged)
        self.player.currentIndexChanged.connect(self.playlistIdxChanged)
        self.playlist = {}

        self.setFixedWidth(900)
        self.setFixedHeight(600)

        layout = QVBoxLayout()
        hlayout = QHBoxLayout()

        hlayout2 = QHBoxLayout()
        self.labelCover = QLabel()
        self.labelCover.setFixedWidth(200)
        self.labelCover.setFixedHeight(200)
        hlayout2.addWidget(self.labelCover)

        vlayout2 = QVBoxLayout()
        vlayout2.addStretch()
        self.labelTitle = QLabel()
        self.labelTitle.setWordWrap(True)
        vlayout2.addWidget(self.labelTitle)
        self.labelAlbum = QLabel()
        self.labelAlbum.setWordWrap(True)
        vlayout2.addWidget(self.labelAlbum)
        self.labelArtist = QLabel()
        self.labelArtist.setWordWrap(True)
        self.labelArtist.setFixedWidth(300)
        vlayout2.addWidget(self.labelArtist)
        vlayout2.addStretch()
        hlayout2.addLayout(vlayout2)

        controlArea = QVBoxLayout()  
        seekSliderLayout = QHBoxLayout()
        controls = QHBoxLayout()
        playlistCtrlLayout = QHBoxLayout()
        
        #creating buttons
        pixmap = QPixmap("pause-play-button.png")
        buttonIcon = QIcon(pixmap)
        self.pauseBtn = QPushButton()
        self.pauseBtn.setIcon(buttonIcon)
        self.pauseBtn.setIconSize(pixmap.rect().size())
        pixmap = QPixmap("stop-button.png")
        buttonIcon = QIcon(pixmap)
        self.stopBtn = QPushButton()
        self.stopBtn.setIcon(buttonIcon)
        self.stopBtn.setIconSize(pixmap.rect().size())
        pixmap = QPixmap("volumedown-button.png")
        buttonIcon = QIcon(pixmap)
        self.volumeDescBtn = QPushButton()
        self.volumeDescBtn.setIcon(buttonIcon)
        self.volumeDescBtn.setIconSize(pixmap.rect().size())
        pixmap = QPixmap("volumeup-button.png")
        buttonIcon = QIcon(pixmap)
        self.volumeIncBtn = QPushButton()
        self.volumeIncBtn.setIcon(buttonIcon)
        self.volumeIncBtn.setIconSize(pixmap.rect().size())

        self.progress = QProgressBar()
        self.progress.setRange(0, 100)
        self.progress.setTextVisible(True)
        self.progress.setValue(self.player.player.volume())
        
        #creating playlist controls
        pixmap = QPixmap("previous-track-button.png")
        buttonIcon = QIcon(pixmap)
        self.prevBtn = QPushButton()
        self.prevBtn.setIcon(buttonIcon)
        self.prevBtn.setIconSize(pixmap.rect().size())
        
        vlayout3 = QVBoxLayout()
        self.labelPlaylist = QLabel()
        self.labelPlaylist.setAlignment(Qt.AlignCenter)
        self.labelPlaylist.setText("No Songs")
        vlayout3.addWidget(self.labelPlaylist)
        pixmap = QPixmap("playlist-button.png")
        buttonIcon = QIcon(pixmap)
        self.playlistBtn = QPushButton()
        self.playlistBtn.setIcon(buttonIcon)
        self.playlistBtn.setIconSize(pixmap.rect().size())
        self.playlistBtn.setCheckable(True)
        vlayout3.addWidget(self.playlistBtn)
        pixmap = QPixmap("next-track-button.png")
        buttonIcon = QIcon(pixmap)
        self.nextBtn = QPushButton()
        self.nextBtn.setIcon(buttonIcon)
        self.nextBtn.setIconSize(pixmap.rect().size())

        #creating seek slider
        self.seekSlider = QSlider()
        self.seekSlider.setMinimum(0)
        self.seekSlider.setMaximum(100)
        self.seekSlider.setOrientation(Qt.Horizontal)
        self.seekSlider.setTracking(False)
        self.seekSlider.sliderMoved.connect(self.seekPosition)
        #self.seekSlider.valueChanged.connect(self.seekPosition)
        
        self.seekSliderLabel1 = QLabel('0.00')
        self.seekSliderLabel2 = QLabel('0.00')
        seekSliderLayout.addWidget(self.seekSliderLabel1)
        seekSliderLayout.addWidget(self.seekSlider)
        seekSliderLayout.addWidget(self.seekSliderLabel2)
        
        #Add handler for each button. Not using the default slots.
        self.pauseBtn.clicked.connect(self.play)
        self.stopBtn.clicked.connect(self.player.stopHandler)
        self.volumeDescBtn.clicked.connect(self.player.decreaseVolume)
        self.volumeIncBtn.clicked.connect(self.player.increaseVolume)
        
        #Adding to the horizontal layout
        controls.addWidget(self.volumeDescBtn)
        controls.addWidget(self.pauseBtn)
        controls.addWidget(self.stopBtn)
        controls.addWidget(self.volumeIncBtn)
        
        #playlist control button handlers
        self.prevBtn.clicked.connect(self.player.prevItemPlaylist)
        self.nextBtn.clicked.connect(self.player.nextItemPlaylist)
        self.playlistBtn.clicked.connect(self.showPlaylist)
        playlistCtrlLayout.addWidget(self.prevBtn)
        playlistCtrlLayout.addLayout(vlayout3)
        playlistCtrlLayout.addWidget(self.nextBtn)
        
        #Adding to the vertical layout
        controlArea.addLayout(seekSliderLayout)
        controlArea.addLayout(controls)
        controlArea.addWidget(self.progress)
        controlArea.addLayout(playlistCtrlLayout)
        hlayout2.addLayout(controlArea)
        layout.addLayout(hlayout2)

        self.stack = QStackedWidget()
        self.view = QTableView()
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.proxy = MyProxyModel()
        self.proxy.setSourceModel(self.db.model)
        self.view.setModel(self.proxy)
        self.view.hideColumn(0)
        self.view.hideColumn(4)
        self.view.hideColumn(5)
        self.view.hideColumn(6)
        self.view.hideColumn(7)
        self.view.hideColumn(9)
        self.view.hideColumn(10)
        self.view.hideColumn(11)
        self.view.selectionModel().selectionChanged.connect(self.viewSelection)
        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.contextMenuEvent)
        self.view.resizeColumnsToContents()
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.setSortingEnabled(True)
        self.view.verticalHeader().setVisible(False)
        self.stack.addWidget(self.view)
        self.viewpl = QListView()
        self.modelpl = QStandardItemModel()
        self.viewpl.setModel(self.modelpl)
        self.stack.addWidget(self.viewpl)
        layout.addWidget(self.stack)
        
        hlayout2 = QHBoxLayout()
        pixmap = QPixmap("search-button.png")
        buttonIcon = QIcon(pixmap)
        self.pushButton_2 = QPushButton()
        self.pushButton_2.setIcon(buttonIcon)
        self.pushButton_2.setIconSize(pixmap.rect().size())
        hlayout2.addWidget(self.pushButton_2)
        self.lineEdit = QLineEdit()
        hlayout2.addWidget(self.lineEdit)
        layout.addLayout(hlayout2)
#        
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
#
#        self.status = QStatusBar()
#        self.setStatusBar(self.status)
#
#        # Uncomment to disable native menubar on Mac
        self.menuBar().setNativeMenuBar(False)
#
#        file_toolbar = QToolBar("File")
#        file_toolbar.setIconSize(QSize(14, 14))
#        self.addToolBar(file_toolbar)
        file_menu = self.menuBar().addMenu("&File")

        add_file_action = QAction("Upload file...", self) #QIcon(os.path.join('images', 'blue-folder-open-document.png')), "Open file...", self)
        add_file_action.setStatusTip("Upload file")
        add_file_action.triggered.connect(self.addFile)
        file_menu.addAction(add_file_action)

        save_file_action = QAction("Remove file..", self)
        save_file_action.setStatusTip("Remove Selected File")
        save_file_action.triggered.connect(self.removeFile)
        file_menu.addAction(save_file_action)

#
#        saveas_file_action = QAction(QIcon(os.path.join('images', 'disk--pencil.png')), "Save As...", self)
#        saveas_file_action.setStatusTip("Save current page to specified file")
#        saveas_file_action.triggered.connect(self.file_saveas)
#        file_menu.addAction(saveas_file_action)
#        file_toolbar.addAction(saveas_file_action)
#
#        print_action = QAction(QIcon(os.path.join('images', 'printer.png')), "Print...", self)
#        print_action.setStatusTip("Print current page")
#        print_action.triggered.connect(self.file_print)
#        file_menu.addAction(print_action)
#        file_toolbar.addAction(print_action)
#
#        edit_toolbar = QToolBar("Edit")
#        edit_toolbar.setIconSize(QSize(16, 16))
#        self.addToolBar(edit_toolbar)
#        edit_menu = self.menuBar().addMenu("&Edit")
#
#        undo_action = QAction(QIcon(os.path.join('images', 'arrow-curve-180-left.png')), "Undo", self)
#        undo_action.setStatusTip("Undo last change")
#        undo_action.triggered.connect(self.editor.undo)
#        edit_menu.addAction(undo_action)
#
#        redo_action = QAction(QIcon(os.path.join('images', 'arrow-curve.png')), "Redo", self)
#        redo_action.setStatusTip("Redo last change")
#        redo_action.triggered.connect(self.editor.redo)
#        edit_toolbar.addAction(redo_action)
#        edit_menu.addAction(redo_action)
#
#        edit_menu.addSeparator()
#
#        cut_action = QAction(QIcon(os.path.join('images', 'scissors.png')), "Cut", self)
#        cut_action.setStatusTip("Cut selected text")
#        cut_action.setShortcut(QKeySequence.Cut)
#        cut_action.triggered.connect(self.editor.cut)
#        edit_toolbar.addAction(cut_action)
#        edit_menu.addAction(cut_action)
#
#        copy_action = QAction(QIcon(os.path.join('images', 'document-copy.png')), "Copy", self)
#        copy_action.setStatusTip("Copy selected text")
#        cut_action.setShortcut(QKeySequence.Copy)
#        copy_action.triggered.connect(self.editor.copy)
#        edit_toolbar.addAction(copy_action)
#        edit_menu.addAction(copy_action)
#
#        paste_action = QAction(QIcon(os.path.join('images', 'clipboard-paste-document-text.png')), "Paste", self)
#        paste_action.setStatusTip("Paste from clipboard")
#        cut_action.setShortcut(QKeySequence.Paste)
#        paste_action.triggered.connect(self.editor.paste)
#        edit_toolbar.addAction(paste_action)
#        edit_menu.addAction(paste_action)
#
#        select_action = QAction(QIcon(os.path.join('images', 'selection-input.png')), "Select all", self)
#        select_action.setStatusTip("Select all text")
#        cut_action.setShortcut(QKeySequence.SelectAll)
#        select_action.triggered.connect(self.editor.selectAll)
#        edit_menu.addAction(select_action)

        self.setWindowTitle("Music DB")
#        self.setWindowIcon(QIcon('stemma.png'))

        self.show()

        #self.pushButton.clicked.connect(self.play)
        self.pushButton_2.clicked.connect(self.searchSong)

    @pyqtSlot('QPoint')
    def contextMenuEvent(self, pos):
        if self.view.selectionModel().selection().indexes():
            for i in self.view.selectionModel().selection().indexes():
                row, column = i.row(), i.column()
            menu = QMenu()
            updateAction = menu.addAction("Update Info")
            addAction = menu.addAction("Add to Playlist")
            newAction = menu.addAction("New Playlist")
            delAction = menu.addAction("Delete Playlist")
            
            action = menu.exec_(self.view.mapToGlobal(pos))
            if action == addAction:
                self.addToPlayList(row, column, False)
            elif action == updateAction:
                self.updateInfo(row, column)
            elif action == newAction:
                self.addToPlaylist(row, column, True)
            elif action == delAction:
                self.delPlaylist()

    def delPlaylist(self):
        self.playlist = {}
        self.labelPlaylist.setText('No Songs')
        self.modelpl.clear()
        
    def addToPlayList(self, row, column, isnew):
        if isnew:
            self.delPlaylist()
        file_id = int(self.db.model.record(row).field(11).value())
        link = self.box.url(file_id)
        self.playlist[link] = self.db.model.record(row)
        #txt = "{} - {}".format(self.db.model.record(row).field(1).value(),
        #                       self.db.model.record(row).field(3).value())
        if len(self.playlist) == 1:
            self.labelPlaylist.setText('1 Song')
        else:
            self.labelPlaylist.setText('{} Songs'.format(len(self.playlist)))
        item = ComponentItem(self.db.model.record(row))
        self.modelpl.appendRow(item)
    
    def updateInfo(self, row, column):
        pass

    @pyqtSlot()
    def searchSong(self):
        pattern = {'search':self.lineEdit.text()}
        self.db.model.setFilter("title like '%{search}%' or artist like '%{search}%' or album like '%{search}%'".format(**pattern))

    @pyqtSlot()
    def startUpdate(self):
        self.w = QtWaitingSpinner(self)
        self.w.start()

    @pyqtSlot()
    def endUpdate(self):
        self.w.stop()
        QMessageBox.information(None, "File Upload", "File {} uploaded.".format(self.box.update_thread.new_filename))
        
    @pyqtSlot()
    def addFile(self):
        filter = "(All Files (*);;MP3 (*.mp3);;M4A (*.m4a)"
        file_name = QFileDialog()
        file_name.setFileMode(QFileDialog.ExistingFiles)
        names = file_name.getOpenFileNames(None, "File Upload", "/Users/sani/Music", filter)
        if len(names[0]) != 0:
            for path in names[0]:
                self.box.upload(path)

    @pyqtSlot()
    def removeFile(self):
        if self.view.selectionModel().hasSelection():
            row = self.view.selectionModel().currentIndex().row()
            file_id = int(self.db.model.record(row).field(11).value())
            self.box.remove(file_id)
            self.db.removeFile(row)
            
    def changeView(self, record):
        self.labelTitle.setText("Title: {}".format(record.field(1).value()))
        self.labelArtist.setText("Artist: {}".format(record.field(3).value()))
        self.labelAlbum.setText("Album: {}".format(record.field(2).value()))
        filename = "covers/{}.jpg".format(record.field(0).value())
        image = QPixmap(filename)
        if not image.isNull():
            self.labelCover.setPixmap(image.scaled(self.labelCover.width(),
                                                   self.labelCover.height(),
                                                   Qt.KeepAspectRatio))
        else:
            self.labelCover.setPixmap(QPixmap())
        self.repaint()
        self.update()
            
    @pyqtSlot(QItemSelection, QItemSelection)
    def viewSelection(self, new, old):
        indices = new.indexes()
        if indices == []:
            return
        record = self.db.model.record(indices[0].row())
        self.changeView(record)
        
    @pyqtSlot()
    def showPlaylist(self):
        if self.playlistBtn.isChecked():
            self.stack.setCurrentIndex(1)
            if len(self.playlist) != 0:
                print ("song", self.player.currentSong)
                record = self.modelpl.item(self.player.currentSong).record
                self.changeView(record)
        else:
            self.stack.setCurrentIndex(0)
            if self.view.selectionModel().hasSelection():
                row = self.view.selectionModel().currentIndex().row()
                print (row)
                self.changeView(self.db.model.record(row))                
        
    @pyqtSlot()
    def play(self):
        if self.player.userAction <= 0:
            if len(self.playlist) != 0:
                self.player.setPlaylist(self.playlist)
            elif self.view.selectionModel().hasSelection():
                row = self.view.selectionModel().currentIndex().row()
                file_id = int(self.db.model.record(row).field(11).value())
                link = self.box.url(file_id)
                self.player.playHandler(link)
        elif self.player.userAction == 1:
            self.player.pauseHandler()
        elif self.player.userAction == 2:
            self.player.playHandler()

    @pyqtSlot(int)
    def seekPosition(self, position):
        sender = self.sender()
        if isinstance(sender, QSlider):
            if self.player.player.isSeekable():
                self.player.player.setPosition(position)

#    @pyqtSlot('qint64', bool)
    def qmp_positionChanged(self, position, senderType=False):
        if senderType == False:
            self.seekSlider.setValue(position)
        self.seekSliderLabel1.setText('%d:%02d'%(int(position/60000),int((position/1000)%60)))

    @pyqtSlot()
    def qmp_mediaStatusChanged(self):
        if self.player.player.mediaStatus() == QMediaPlayer.LoadedMedia and self.player.userAction == 1:
            durationT = self.player.player.duration()
            self.seekSlider.setRange(0, durationT)
            self.seekSliderLabel2.setText('%d:%02d'%(int(durationT/60000),int((durationT/1000)%60)))
            self.player.player.play()
            # FIXME FARE UNA FUNZIONE ????
            if len(self.playlist) != 0:
                record = self.modelpl.item(self.player.currentSong).record
                
            else:
                if self.view.selectionModel().hasSelection():
                    row = self.view.selectionModel().currentIndex().row()
            #rate = record.field(8).value()
            #self.db.incrementPlayed()

    @pyqtSlot()
    def qmp_stateChanged(self):
        if self.player.player.state() == QMediaPlayer.StoppedState:
            self.player.player.stop()
            self.player.stopHandler()
                                                        
    def qmp_volumeChanged(self):
        self.progress.setValue(self.player.player.volume())

    @pyqtSlot(int, int)
    def playlistIdxChanged(self, old, new):
        if len(self.playlist) > 0:
            if old != -1:
                self.modelpl.item(old).selected = False
            if new != -1:
                self.modelpl.item(new).selected = True

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message', 'Are you sure ?', QMessageBox.Yes|QMessageBox.No, QMessageBox.Yes)
        if reply == QMessageBox.Yes :
            self.close()
        else:
            try:
                event.ignore()
            except AttributeError:
                pass
Exemplo n.º 7
0
                        default=1)
    args = parser.parse_args()

    n = args.size
    times = args.times
    players = [args.player1, args.player2]
    player_objs = []
    for player in players:
        if player.lower() == 'random':
            player_objs.append(RandomPlayer())
        elif player.lower() == 'manual':
            player_objs.append(ManualPlayer())
        elif player.lower() == 'greedy':
            player_objs.append(GreedyPlayer())
        elif player.lower() == 'my':
            player_objs.append(MyPlayer())
        else:
            print('Wrong player type. Options: manual, random, greedy, my')
            sys.exit()

    black_wins = white_wins = 0
    for time in range(times):
        player1, player2 = player_objs[0], player_objs[1]
        my_go = GO(n)
        result = my_go.play(player1, player2)
        if result == 1: black_wins += 1
        elif result == 2: white_wins += 1
    print()
    print('Black player (X) | Wins:{0:.1f}% Loses:{1:.1f}%'.format(
        100 * black_wins / times, 100 * white_wins / times))
    print('White player (O) | Wins:{0:.1f}% Loses:{1:.1f}%'.format(
Exemplo n.º 8
0
                zeroes += 1
    if zeroes > ones:
        return 0, zeroes, ones
    elif ones > zeroes:
        return 1, ones, zeroes
    else:
        return 2, ones, zeroes


if __name__ == "__main__":
    player1_wins = 0
    player2_wins = 0
    ties = 0
    for i in range(10):
        player1 = MyPlayerMobilityAndScore(0, 1)
        player2 = MyPlayer(1, 0)
        board = init_board()
        passed = 0
        if comments:
            print_board(board)
        while not board_full(board) and not passed >= 2:
            x, y = player1.move(board)
            if not (x == -1 and y == -1):
                passed = 0
                board = flip(board, x, y, 0, 1)
                if comments:
                    print("Player 1 moves to:", x, ":", y)
                    print_board(board)
            else:
                passed += 1
            x, y = player2.move(board)
Exemplo n.º 9
0
class Prompt(Cmd, object):
    """ Handle user input """
    def __init__(self, conn_string):
        super(Prompt, self).__init__()

        # Build database connection
        self.conn = psycopg2.connect(conn_string)
        self.cur = self.conn.cursor(
            cursor_factory=psycopg2.extras.DictCursor
        )  #create database cursor. parameter grabs result as dict (which is not default)
        self.conn.autocommit = True  #disable transactions (transactions left uncommitted will hang the game)

        self.myplayer = MyPlayer(self.cur)
        self.game = Game(self.cur)
        self.armada = Armada(self.cur)

    def do_attack_all(self, args):
        """ Order all ships in range of enemy ships to attack """

        # Order the attack
        self.armada.attack_all()
        print("[+] All ships in attack range ordered to attack")

    def do_mine_all(self, args):
        """ Order all ships in range of planets to mine """

        # Order the mine
        self.armada.mine_all()
        print("[+] All ships in mining range ordered to mine")

    def do_mystatus(self, args):
        """ Status of the player """

        self.myplayer.update()

        print("[+] User      | Balance | Fuel Reserve")
        print("    ----------------------------------")
        print("    " + str(self.myplayer.username) + " | " + \
            str(self.myplayer.balance) + " | " + \
            str(self.myplayer.fuel_reserve))

    def do_planets(self, args):
        """ Show the list of planets """

        # Check if table scan is necessary
        if self.game.count_planets() != len(self.game.planets):
            print("[+] Planet count off, initiating table scan")
            self.game.update_planets()
            print("[+] Done")

        print("[+] ID    | Name   | Mine Limit | Loc X | Loc Y | Conqueror")
        print("    -------------------------------------------------------")
        for i in self.game.planets:
            print("    " + str(i.planet_id) + " | " + \
                str(i.name) + " | " + \
                str(i.mine_limit) + " | " + \
                str(i.location_x) + " | " + \
                str(i.location_y) + " | " + \
                str(i.conqueror))

    def do_planets_in_range(self, args):
        """ Dump table of planets in range """

        planets = self.armada.planets_in_range()

        print("[+] Ship ID | Planet ID")
        print("    -------------------")
        for p in planets:
            print("[+] " + str(p) + " | " + str(planets[p]))

    def do_planets_update(self, args):
        """ For an update for the planets """

        self.game.update_planets()
        print("[+] Planets updated")

    def do_players(self, args):
        """ Show all players """

        self.game.update_players()

        print(
            "[+] ID | Username   | Damage Taken | Damage Done | Planets Conq | Planets Lost | Ships Built | Ships Lost | Ship Upgrades | Distance | Fuel Mined"
        )
        print(
            "    ---------------------------------------------------------------------------------------------------------------------------------------------"
        )
        for i in self.game.players:
            print("    " + str(i.player_id) + " | " + \
                str(i.username) + " | " + \
                str(i.damage_taken) + " | " + \
                str(i.damage_done) + " | " + \
                str(i.planets_conquered) + " | " + \
                str(i.planets_lost) + " | " + \
                str(i.ships_built) + " | " + \
                str(i.ships_lost) + " | " + \
                str(i.ship_upgrades) + " | " + \
                str(i.distance_travelled) + " | " + \
                str(i.fuel_mined))

    def do_ship_attack(self, args):
        """ Attack a target ship with your own ships
            ship_attack [ship id] [target id] """

        # Create a list from the argument string
        arg_list = args.split(' ')

        # Check argument list
        if len(args) == 0:
            print("[-] Error: argument list cannot be empty")
        elif len(arg_list) != 2:
            print("[-] Error: argument list incorrect")
        else:
            self.armada.attack(arg_list[0], arg_list[1])
            print("[+] Ships with identifier " + str(arg_list[0]) +
                  " set to attack " + str(arg_list[1]))

    def do_ship_create(self, args):
        """ Create a ship
            ship_create [name]
            ship_create [name] [attack] [defense] [engineering] [prospecting] [planet id]
            ship_create [name] [attack] [defense] [engineering] [prospecting] [location_x] [location_y] """

        # Create a list from the argument string
        arg_list = args.split(' ')

        # Check the arguments
        if len(args) == 0:
            print("[-] Error: argument list cannot be empty")
        elif len(arg_list) > 7:
            print("[-] Error: argument list too long")
        else:
            # Set ship name
            name = arg_list[0]

            # Set ship attrs and location if offered
            stats = []
            if len(arg_list) == 1:
                stats.append(5)
                stats.append(5)
                stats.append(5)
                stats.append(5)
                location = ""
            else:
                stats.append(arg_list[1])
                stats.append(arg_list[2])
                stats.append(arg_list[3])
                stats.append(arg_list[4])
                if len(arg_list) == 6:
                    # Get coordinates from planet id
                    for planet in self.game.planets:
                        if arg_list[5] == str(planet.planet_id):
                            location = str(planet.location_x) + "," + str(
                                planet.location_y)
                else:
                    # Get coordinates from args
                    location = arg_list[5] + "," + arg_list[6]

            # Create the ship
            self.armada.create(name, stats, location)

    def do_ship_mine(self, args):
        """ Order a ship in range of a planet to mine
            ship_mine [ship id] [planet id] """

        # Create a list from the argument string
        arg_list = args.split(' ')

        # Check argument list
        if len(args) == 0:
            print("[-] Error: argument list cannot be empty")
        elif len(arg_list) != 2:
            print("[-] Error: argument list incorrect")
        else:
            self.armada.mine(arg_list[0], arg_list[1])
            print("[+] Ship with id " + str(arg_list[0]) +
                  " ordered to mine planet id " + str(arg_list[1]))

    def do_ship_move(self, args):
        """ Move a ship at a speed towards a point
            ship_move [ship id] [max|half] [planet id]
            ship_move [ship id] [max|half] [location_x] [location_y] """

        # Create a list from the argument string
        arg_list = args.split(' ')

        # Check argument list
        if len(args) == 0:
            print("[-] Error: argument list cannot be empty")
        elif len(arg_list) > 4:
            print("[-] Error: argument list too long")
        else:
            if len(arg_list) == 3:
                # Get coordinates from planet id
                for planet in self.game.planets:
                    if arg_list[2] == str(planet.planet_id):
                        location_x = str(planet.location_x)
                        location_y = str(planet.location_y)
            else:
                # Get coordinates from args
                location_x = arg_list[2]
                location_y = arg_list[3]
            self.armada.move(arg_list[0], arg_list[1], location_x, location_y)
            print("[+] Ship with id " + str(arg_list[0]) + " moved to POINT(" +
                  location_x + "," + location_y + ")")

    def do_ship_repair(self, args):
        """ Order a ship in range of a target ship to repair
            ship_repair [source ship id] [target ship id] """

        # Check argument list
        if len(args) == 0:
            print("[-] Error: argument list cannot be empty")
        elif len(args.split()) != 2:
            print("[-] Error: argument list incorrect")
        else:
            arglist = args.split()
            self.armada.repair(arglist[0], arglist[1])
            print("[+] Ship with id " + str(arglist[0]) +
                  " ordered to repair id " + str(arglist[1]))

    def do_ship_upgrade(self, args):
        """ Upgrade an attribute of a ship
            ship_upgrade [id] [attribute] [quantity]
            Attributes:
            MAX_HEALTH  MAX_FUEL  MAX_SPEED  RANGE
            ATTACK  DEFENSE  ENGINEERING PROSPECTING"""

        # Create a list from the argument string
        arg_list = args.split(' ')

        # Check argument list
        if len(args) == 0:
            print("[-] Error: argument list cannot be empty")
        elif len(arg_list) != 3:
            print("[-] Error: argument list incorrect")
        else:
            for ship in self.armada.ships:
                if ship.ship_id == int(arg_list[0]):
                    ship.upgrade(arg_list[1], arg_list[2])
                    print("[+] Ship with id " + str(arg_list[0]) + " upgraded")

    def do_ships(self, args):
        """ Show ships """

        self.armada.update()

        print(
            "[+] ID | fleet_id | player_id | name | last_action_tic | last_move_tic | last_living_tic | current_health | max_health | current_fuel | max_fuel | max_speed | range | attack | defense | engineering | prospecting | location_x | location_y | direction | speed | destination_x | destination_y | repair_priority | action | action_target_id |      location      | destination | target_speed | target_direction"
        )
        print("    -------------------")
        for ship in self.armada.ships:
            print("    " + str(ship.ship_id) + " | " + \
                str(ship.fleet_id) + " | " + \
                str(ship.player_id) + " | " + \
                str(ship.name) + " | " + \
                str(ship.last_action_tic) + " | " + \
                str(ship.last_move_tic) + " | " + \
                str(ship.last_living_tic) + " | " + \
                str(ship.current_health) + " | " + \
                str(ship.max_health) + " | " + \
                str(ship.current_fuel) + " | " + \
                str(ship.max_fuel) + " | " + \
                str(ship.max_speed) + " | " + \
                str(ship.range) + " | " + \
                str(ship.attack) + " | " + \
                str(ship.defense) + " | " + \
                str(ship.engineering) + " | " + \
                str(ship.prospecting) + " | " + \
                str(ship.location_x) + " | " + \
                str(ship.location_y) + " | " + \
                str(ship.direction) + " | " + \
                str(ship.speed) + " | " + \
                str(ship.destination_x) + " | " + \
                str(ship.destination_y) + " | " + \
                str(ship.repair_priority) + " | " + \
                str(ship.action) + " | " + \
                str(ship.action_target_id) + " | " + \
                str(ship.location) + " | " + \
                str(ship.destination) + " | " + \
                str(ship.target_speed) + " | " + \
                str(ship.target_direction))

    def do_ships_in_range(self, args):
        """ Dump table of ships in range """

        ships = self.armada.ships_in_range()

        print("[+] Ship ID | Target Ship ID(s)")
        print("    ---------------------------")
        for s in ships:
            print("    " + str(s) + " | " + str(ships[s]))

    def do_tic(self, args):
        """ Get current server Tic """

        self.game.update_tic()
        print("[+] Current Tic: " + str(self.game.tic))

    def do_variables(self, args):
        """ Update and dump variables """

        self.game.update_variables()
        print("[+] Name | Value")
        print("    ------------")
        for key, value in self.game.variables.items():
            print("    " + str(key) + "|" + str(value))

    def do_quit(self, args):
        """ Quit the program """

        print("[+] Shutting down")

        # Close down database connection
        self.conn.commit()
        self.cur.close()
        self.conn.close()

        raise SystemExit