class ProgressBar(QWidget):
    def __init__(self,parent=None):
        super(ProgressBar, self).__init__(parent)
        self.initUI()
    def initUI(self):
        self.pbar=QProgressBar(self)
        self.pbar.setGeometry(40,40,200,25)

        self.btn=QPushButton('开始',self)
        self.btn.move(40,80)
        self.btn.clicked.connect(self.doAction)

        self.timer=QBasicTimer()
        self.value=0
        self.setGeometry(300,300,280,170)
        self.setWindowTitle('QProgressBar控件')
        self.show()
    def timerEvent(self, e):    #递归?
        if self.value>=100:
            self.timer.stop()
            self.btn.setText('完成')
            return
        self.value=self.value+1
        self.pbar.setValue(self.value)

    def doAction(self):
        if self.timer.isActive():
            self.timer.stop()
            self.btn.setText('开始')
        else:
            self.timer.start(100,self)
            self.btn.setText('停止')
Esempio n. 2
0
class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        vbox = QVBoxLayout()

        self.pbar = QProgressBar()  # 3.04 加入布局可省略self !!!
        # self.pbar.setGeometry(30, 40, 200, 25)
        vbox.addWidget(self.pbar)

        self.btn = QPushButton('Start')
        # self.btn.move(40, 80)
        self.btn.clicked.connect(self.doAction)  # 6.02 对比click[bool]
        vbox.addWidget(self.btn)

        self.setLayout(vbox)

        self.timer = QBasicTimer()
        self.step = 0

        self.setGeometry(300, 300, 600, 400)
        self.setWindowTitle('QPressBar')
        self.show()

    # 重写原生槽函数. 没过一个单位时间, 执行一次
    def timerEvent(self, event):

        # 到达100%时, 即便点了按钮, 也会马上变为Finished
        if self.step >= 100:
            self.timer.stop()
            self.btn.setText('Finished')
            return

        self.step = self.step + 1
        self.pbar.setValue(self.step)

    def doAction(self):

        if self.timer.isActive():
            self.timer.stop()
            self.btn.setText('Start')
        else:
            self.timer.start(100, self)  # 绑定self, 为self及时, 时限100s
            self.btn.setText('Stop')
class WigglyWidget(QWidget):
    def __init__(self, parent=None):
        super(WigglyWidget, self).__init__(parent)
        self.step = 0
        self.text = ""
        self.setBackgroundRole(QPalette.Midlight)
        self.setAutoFillBackground(True)

        newFont = self.font()
        newFont.setPointSize(newFont.pointSize() + 20)
        self.setFont(newFont)

        self.timer = QBasicTimer()
        self.timer.start(60, self)

    def paintEvent(self, event):
        sineTable = [
            0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71,
            -38
        ]

        metrics = QFontMetrics(self.font())
        x = (self.width() - metrics.horizontalAdvance(self.text)) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        color = QColor()

        painter = QPainter(self)
        for i in range(len(self.text)):
            index = (self.step + i) % 16
            color.setHsv((15 - index) * 16, 255, 191)
            painter.setPen(color)
            painter.drawText(x,
                             y - ((sineTable[index] * metrics.height()) / 400),
                             str(self.text[i]))
            x += metrics.horizontalAdvance(self.text[i])

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            self.step += 1
            self.update()
        else:
            QWidget.timerEvent(event)

    def setText(self, text):
        self.text = text
class gui(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setGeometry(300, 300, 300, 300)
        self.setFixedSize(300, 300)
        self.setWindowTitle('libmapper device gui example')
        blurb = QLabel(
            'These sliders will be dynamically labeled with the name of destination signals to which they are connected.',
            self)
        blurb.setGeometry(5, 0, 290, 50)
        blurb.setWordWrap(True)

        self.labels = []
        self.sliders = []
        for i in range(numsliders):
            self.sliders.append(QSlider(Qt.Orientation.Horizontal, self))
            self.sliders[i].setRange(0, 100)
            self.sliders[i].setGeometry(5, 100 + i * 75, 290, 20)
            self.labels.append(QLabel('slider%i' % i, self))
            self.labels[i].setGeometry(5, 75 + i * 75, 290, 15)

        self.sliders[0].valueChanged.connect(
            lambda x: sigs[0].set_value(x * 0.01))
        self.sliders[1].valueChanged.connect(
            lambda x: sigs[1].set_value(x * 0.01))
        self.sliders[2].valueChanged.connect(
            lambda x: sigs[2].set_value(x * 0.01))

        self.timer = QBasicTimer()
        self.timer.start(10, self)

    def setLabel(self, index, label):
        if index < 0 or index > numsliders:
            return
        self.labels[index].setText(label)

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            dev.poll()

        else:
            QtGui.QFrame.timerEvent(self, event)
Esempio n. 5
0
class Window(QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.set_settings()
        self.create_widgets()

    def set_settings(self):
        self.resize(350, 200)

    def create_widgets(self):
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setFixedWidth(300)
        self.progress_bar.move(50, 80)

        # Timer creating
        self.timer = QBasicTimer()
        self.step = 0
        self.timer.start(100, self)

    def timerEvent(self, e):
        if self.step >= 100:
            self.timer.stop()
        self.step += 1
        self.progress_bar.setValue(self.step)
Esempio n. 6
0
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle("Chat Smasher")
        # Create Widgets

        self.edit = QLineEdit("Welcome")
        self.button = QPushButton("Load Files")
        self.stopButton = QPushButton("Stop")
        self.box1 = QComboBox()  # Holds name of files
        self.filePreview = QTextBrowser()  # Preview Files
        self.loadingBar = QProgressBar(self)

        self.preview = QTextBrowser()
        self.champBox = QComboBox()
        self.ConfirmButton = QPushButton("Start")
        # Create layout and add widgets
        layout = QVBoxLayout()

        self.label2 = QLabel()
        self.label2.setText("Caleb's Chat Smasher")
        self.label2.setStyleSheet(
            "QLabel { background-color : green; color : white; font-size: 20px; text-align : "
            "center; }")

        self.label = QLabel()
        pixmap = QPixmap('lek.png')
        self.timer = QBasicTimer()
        self.step = 0
        self.label.setPixmap(pixmap)

        layout.addWidget(self.label2)
        layout.addWidget(self.label)

        #layout.addWidget(self.edit)
        self.champBox = QComboBox()
        # layout.addWidget(self.champBox)
        layout.addWidget(self.button)
        layout.addWidget(self.box1)

        layout.addWidget(self.filePreview)
        layout.addWidget(self.ConfirmButton)
        layout.addWidget(self.stopButton)
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: red}")

        layout.addWidget(self.loadingBar)

        #self.file
        # Set layout
        self.setLayout(layout)
        p = self.palette()
        p.setColor(self.foregroundRole(), QColor(10, 10, 10, 127))
        p.setColor(self.backgroundRole(), QColor(0, 0, 0, 127))

        self.setPalette(p)
        self.setFixedWidth(450)
        self.setFixedHeight(700)

        #make connections
        self.button.clicked.connect(self.imclicked)
        self.ConfirmButton.clicked.connect(self.newStart)
        self.stopButton.clicked.connect(self.stop)
        self.box1.activated.connect(self.updatePreview)

    def start(self):
        print("Ready to Go")
        myFile = pathlib.Path.cwd() / 'copypastas' / self.box1.currentText()
        clicking.type_page(myFile)
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: green } QProgressBar {text-align: center}"
        )

    def stop(self):
        self.timer.stop()
        #self.loadingBar.setValue(0)

    def imclicked(self):
        self.updatelist()

    def newStart(self):
        global stepper
        stepper = 0
        self.loadingBar.setValue(0)
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: red;} QProgressBar {text-align: center}"
        )
        self.startTracking()

    def updatelist(self):
        self.box1.clear()
        fileNames = fileHandling.getFileNames()
        for names in fileNames:
            self.box1.addItem(names)
        self.updatePreview()

    def updatePreview(self):
        self.filePreview.clear()
        myFile = pathlib.Path.cwd() / 'copypastas' / self.box1.currentText()
        with open(myFile, 'r') as pageRead:
            for line in pageRead:
                self.filePreview.append(line)

    def startTracking(self):
        self.timer.start(80, self)

    def timerEvent(self, event):
        global stepper
        stepper += 1
        self.loadingBar.setValue(stepper)
        if self.loadingBar.value() == 100:
            self.start()
            self.timer.stop()
Esempio n. 7
0
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle(
            "Automation.... WITH KITTENS!!!! AHHH I LOVE KITTENS")
        # Create Widgets
        self.fileLoader = QPushButton("Load Files")
        self.stopButton = QPushButton("Stop")
        self.fileBox = QComboBox()  # Holds name of files
        self.filePreview = QTextBrowser()  # Preview Files
        self.loadingBar = QProgressBar(self)
        self.preview = QTextBrowser()
        self.ConfirmButton = QPushButton("Start")
        # Variable Creation Area
        self.pictureDic = {}  # Holds the tings
        self.timerBool = bool
        # Create layout and add widgets
        layout = QVBoxLayout()
        # Design Area
        self.label2 = QLabel()
        self.label2.setText("Automating Kittens!")
        self.label2.setStyleSheet(
            "QLabel { background-color : black; color : white; font-size: 20px; text-align : "
            "center; }")
        self.label = QLabel()
        pixmap = QPixmap('pictures/helloKitten.png')
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.timer = QBasicTimer()
        self.step = 0
        self.label.setPixmap(pixmap)

        # Adding widgets to the layout
        layout.addWidget(self.label2)
        layout.addWidget(self.label)
        layout.addWidget(self.fileLoader)
        layout.addWidget(self.fileBox)
        layout.addWidget(self.filePreview)
        layout.addWidget(self.ConfirmButton)
        layout.addWidget(self.stopButton)
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: red}")
        layout.addWidget(self.loadingBar)
        # Enable Minimize and maximize
        self.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
        self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
        # Set layout
        self.setLayout(layout)
        p = self.palette()
        p.setColor(self.foregroundRole(), QColor(10, 10, 10, 127))
        p.setColor(self.backgroundRole(), QColor(0, 0, 127, 127))
        self.setPalette(p)
        self.setFixedWidth(450)
        self.setFixedHeight(700)
        # Connecting functions to buttons
        self.fileLoader.clicked.connect(self.loadFiles)
        self.ConfirmButton.clicked.connect(self.newStart)
        self.stopButton.clicked.connect(self.stop)
        self.fileBox.activated.connect(self.updatePreview)

    def start(self):
        print("Ready to Go")
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: gold } QProgressBar {text-align: center}"
        )
        if bool(self.pictureDic) is False:
            self.filePreview.append("**** Empty Files **** \n")
            self.filePreview.append("**** Please load Files **** \n")
            self.timer.stop()
        else:
            self.filePreview.append("**** Starting Picture Search **** \n")
            self.searchThread = threadedSearch.thread_with_exception(
                "Searching", self.pictureDic)
            self.searchThread.start()
        pixmap = QPixmap('pictures/pawwingKitten.jpg')
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.label.setPixmap(pixmap)

    def loadFiles(self):
        print("We gone load them files doh")
        self.filePreview.append("**** Files Loaded **** \n")
        self.fileBox.clear()
        self.pictureDic.clear()
        with os.scandir('testpictures/') as files:
            for file in files:
                print(file.path)
                print(file.name)
                self.pictureDic.update({file.name: file.path})
                self.fileBox.addItem(file.name)
                self.filePreview.append("{} \n".format(file.name))
        self.filePreview.append("**** Files done loading **** \n")

    def newStart(self):
        pixmap = QPixmap('pictures/roaringKitten.jpg')
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.label.setPixmap(pixmap)
        self.timerBool = True
        global stepper
        stepper = 0
        self.loadingBar.setValue(0)
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: red;} QProgressBar {text-align: center}"
        )
        self.startTracking()

    def updatePreview(self):
        self.label.clear()
        location = self.pictureDic[self.fileBox.currentText()]
        pixmap = QPixmap('{}'.format(location))
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.timer = QBasicTimer()
        self.step = 0
        self.label.setPixmap(pixmap)

    def startTracking(self):
        self.timer.start(80, self)

    def stop(self):
        self.timer.stop()
        try:
            self.searchThread.raise_exception()
            self.searchThread.join()
            self.filePreview.append("**** Sucessfully Killed thread **** \n")
        except:
            self.filePreview.append("**** No thread to kill! **** \n")
        pixmap = QPixmap('pictures/sadkitten.jpg')
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.label.setPixmap(pixmap)
        self.loadingBar.setValue(0)

    def timerEvent(self, event):
        if self.timerBool is True:
            global stepper
            stepper += 1
            self.loadingBar.setValue(stepper)
            if self.loadingBar.value() == 100:
                self.start()
                self.timerBool = False
                self.loadingBar.setStyleSheet(
                    "QProgressBar::chunk {background-color: green;} QProgressBar {text-align: center}"
                )
        else:
            try:
                printingMess = self.searchThread.getMessage()
                if printingMess != "":
                    self.filePreview.append("{} \n".format(printingMess))
            except:
                self.filePreview.append(
                    " *** No information from Thread *** \n")
class Board(QFrame):

    msg2Statusbar = Signal(str)

    BoardWidth = 10
    BoardHeight = 22
    Speed = 300

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

        self.initBoard()

    def initBoard(self):
        '''initiates board'''

        self.timer = QBasicTimer()
        self.isWaitingAfterLine = False

        self.curX = 0
        self.curY = 0
        self.numLinesRemoved = 0
        self.board = []

        self.setFocusPolicy(Qt.StrongFocus)
        self.isStarted = False
        self.isPaused = False
        self.clearBoard()

    def shapeAt(self, x, y):
        '''determines shape at the board position'''

        return self.board[(y * Board.BoardWidth) + x]

    def setShapeAt(self, x, y, shape):
        '''sets a shape at the board'''

        self.board[(y * Board.BoardWidth) + x] = shape

    def squareWidth(self):
        '''returns the width of one square'''

        return self.contentsRect().width() // Board.BoardWidth

    def squareHeight(self):
        '''returns the height of one square'''

        return self.contentsRect().height() // Board.BoardHeight

    def start(self):
        '''starts game'''

        if self.isPaused:
            return

        self.isStarted = True
        self.isWaitingAfterLine = False
        self.numLinesRemoved = 0
        self.clearBoard()

        self.msg2Statusbar.emit(str(self.numLinesRemoved))

        self.newPiece()
        self.timer.start(Board.Speed, self)

    def pause(self):
        '''pauses game'''

        if not self.isStarted:
            return

        self.isPaused = not self.isPaused

        if self.isPaused:
            self.timer.stop()
            self.msg2Statusbar.emit("paused")

        else:
            self.timer.start(Board.Speed, self)
            self.msg2Statusbar.emit(str(self.numLinesRemoved))

        self.update()

    def paintEvent(self, event):
        '''paints all shapes of the game'''

        painter = QPainter(self)
        rect = self.contentsRect()

        boardTop = rect.bottom() - Board.BoardHeight * self.squareHeight()

        for i in range(Board.BoardHeight):
            for j in range(Board.BoardWidth):
                shape = self.shapeAt(j, Board.BoardHeight - i - 1)

                if shape != Tetrominoe.NoShape:
                    self.drawSquare(painter,
                                    rect.left() + j * self.squareWidth(),
                                    boardTop + i * self.squareHeight(), shape)

        if self.curPiece.shape() != Tetrominoe.NoShape:

            for i in range(4):

                x = self.curX + self.curPiece.x(i)
                y = self.curY - self.curPiece.y(i)
                self.drawSquare(
                    painter,
                    rect.left() + x * self.squareWidth(), boardTop +
                    (Board.BoardHeight - y - 1) * self.squareHeight(),
                    self.curPiece.shape())

    def keyPressEvent(self, event):
        '''processes key press events'''

        if not self.isStarted or self.curPiece.shape() == Tetrominoe.NoShape:
            super(Board, self).keyPressEvent(event)
            return

        key = event.key()

        if key == Qt.Key_P:
            self.pause()
            return

        if self.isPaused:
            return

        elif key == Qt.Key_Left:
            self.tryMove(self.curPiece, self.curX - 1, self.curY)

        elif key == Qt.Key_Right:
            self.tryMove(self.curPiece, self.curX + 1, self.curY)

        elif key == Qt.Key_Down:
            self.tryMove(self.curPiece.rotateRight(), self.curX, self.curY)

        elif key == Qt.Key_Up:
            self.tryMove(self.curPiece.rotateLeft(), self.curX, self.curY)

        elif key == Qt.Key_Space:
            self.dropDown()

        elif key == Qt.Key_D:
            self.oneLineDown()

        else:
            super(Board, self).keyPressEvent(event)

    def timerEvent(self, event):
        '''handles timer event'''

        if event.timerId() == self.timer.timerId():

            if self.isWaitingAfterLine:
                self.isWaitingAfterLine = False
                self.newPiece()
            else:
                self.oneLineDown()

        else:
            super(Board, self).timerEvent(event)

    def clearBoard(self):
        '''clears shapes from the board'''

        for i in range(Board.BoardHeight * Board.BoardWidth):
            self.board.append(Tetrominoe.NoShape)

    def dropDown(self):
        '''drops down a shape'''

        newY = self.curY

        while newY > 0:

            if not self.tryMove(self.curPiece, self.curX, newY - 1):
                break

            newY -= 1

        self.pieceDropped()

    def oneLineDown(self):
        '''goes one line down with a shape'''

        if not self.tryMove(self.curPiece, self.curX, self.curY - 1):
            self.pieceDropped()

    def pieceDropped(self):
        '''after dropping shape, remove full lines and create new shape'''

        for i in range(4):

            x = self.curX + self.curPiece.x(i)
            y = self.curY - self.curPiece.y(i)
            self.setShapeAt(x, y, self.curPiece.shape())

        self.removeFullLines()

        if not self.isWaitingAfterLine:
            self.newPiece()

    def removeFullLines(self):
        '''removes all full lines from the board'''

        numFullLines = 0
        rowsToRemove = []

        for i in range(Board.BoardHeight):

            n = 0
            for j in range(Board.BoardWidth):
                if not self.shapeAt(j, i) == Tetrominoe.NoShape:
                    n = n + 1

            if n == 10:
                rowsToRemove.append(i)

        rowsToRemove.reverse()

        for m in rowsToRemove:

            for k in range(m, Board.BoardHeight):
                for l in range(Board.BoardWidth):
                    self.setShapeAt(l, k, self.shapeAt(l, k + 1))

        numFullLines = numFullLines + len(rowsToRemove)

        if numFullLines > 0:

            self.numLinesRemoved = self.numLinesRemoved + numFullLines
            self.msg2Statusbar.emit(str(self.numLinesRemoved))

            self.isWaitingAfterLine = True
            self.curPiece.setShape(Tetrominoe.NoShape)
            self.update()

    def newPiece(self):
        '''creates a new shape'''

        self.curPiece = Shape()
        self.curPiece.setRandomShape()
        self.curX = Board.BoardWidth // 2 + 1
        self.curY = Board.BoardHeight - 1 + self.curPiece.minY()

        if not self.tryMove(self.curPiece, self.curX, self.curY):

            self.curPiece.setShape(Tetrominoe.NoShape)
            self.timer.stop()
            self.isStarted = False
            self.msg2Statusbar.emit("Game over")

    def tryMove(self, newPiece, newX, newY):
        '''tries to move a shape'''

        for i in range(4):

            x = newX + newPiece.x(i)
            y = newY - newPiece.y(i)

            if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:
                return False

            if self.shapeAt(x, y) != Tetrominoe.NoShape:
                return False

        self.curPiece = newPiece
        self.curX = newX
        self.curY = newY
        self.update()

        return True

    def drawSquare(self, painter, x, y, shape):
        '''draws a square of a shape'''

        colorTable = [
            0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 0xCCCC66, 0xCC66CC,
            0x66CCCC, 0xDAAA00
        ]

        color = QColor(colorTable[shape])
        painter.fillRect(x + 1, y + 1,
                         self.squareWidth() - 2,
                         self.squareHeight() - 2, color)

        painter.setPen(color.lighter())
        painter.drawLine(x, y + self.squareHeight() - 1, x, y)
        painter.drawLine(x, y, x + self.squareWidth() - 1, y)

        painter.setPen(color.darker())
        painter.drawLine(x + 1, y + self.squareHeight() - 1,
                         x + self.squareWidth() - 1,
                         y + self.squareHeight() - 1)
        painter.drawLine(x + self.squareWidth() - 1,
                         y + self.squareHeight() - 1,
                         x + self.squareWidth() - 1, y + 1)
Esempio n. 9
0
class TapeWidget(QWidget):

    X_MARGIN = 0.0
    Y_MARGIN = 5.0

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        self._timer = QBasicTimer()
        self._move = 0
        self._displace = 0
        self._seek_accel = 0
        self._header_pos = 0
        self._is_seeking = False
        self._speed = 1.0
        # self._font = QFont("monospaced")
        # self._font.setStyleHint(QFont.TypeWriter)
        # self._font.setPointSize(11)

    @property
    def speed(self):
        return self._speed

    @speed.setter
    def speed(self, value: float):
        if value <= 0:
            raise
        self._speed = value

    def move_to(self, position: int):
        if self._header_pos == position and self._move == position:
            return
        self._move = position
        self._is_seeking = True
        self._seek_accel = abs(self._header_pos - position) * self._speed
        if not self._timer.isActive():
            self._timer.start(10, self)
        self.update()

    def move_right(self):
        self.move_to(self._move + 1)

    def move_left(self):
        self.move_to(self._move - 1)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Left:
            self.move_left()
        elif event.key() == Qt.Key_Right:
            self.move_right()

    def timerEvent(self, event):
        if not self._is_seeking:
            self._timer.stop()
            return
        if self._move < self._header_pos:
            self._displace += self._seek_accel
            if abs(self._displace) >= 20:
                self._header_pos -= 1
                self._displace = 0
        else:
            self._displace -= self._seek_accel
            if abs(self._displace) >= 20:
                self._header_pos += 1
                self._displace = 0

        if self._header_pos == self._move:
            self._timer.stop()
            self._is_seeking = False
        self.update()

    def sizeHint(self):
        return self.minimumSizeHint()

    def minimumSizeHint(self):
        return QSize(0, 40)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setPen(Qt.white)
        painter.setBrush(Qt.white)
        painter.drawRect(event.rect())
        painter.setPen(Qt.lightGray)
        r = QRect(event.rect()).adjusted(TapeWidget.X_MARGIN,
                                         TapeWidget.Y_MARGIN,
                                         -TapeWidget.X_MARGIN,
                                         -TapeWidget.Y_MARGIN)
        # Draw tape
        painter.fillRect(r, QColor(Qt.gray).light(150))
        painter.drawLine(r.topLeft(), r.topRight())
        painter.drawLine(r.bottomLeft(), r.bottomRight())

        fm = QFontMetrics(self.font())
        center = QPoint(self.width() / 2, self.height() / 2)

        cw = fm.width(' ') + 15
        # ch = fm.height() + 5

        x = self._displace + center.x() + cw / 2
        while x > 0:
            x -= cw
            painter.drawLine(x, r.y() + 5, x, r.bottom() - 5)

        x = self._displace + center.x() - cw / 2
        while x < self.width():
            x += cw
            painter.drawLine(x, r.y() + 5, x, r.bottom() - 5)

        # Draw head
        color = QColor('#00a8ff')
        color.setAlpha(100)
        painter.setBrush(color)
        painter.drawRect(center.x() - 15, 3, 29, 33)
Esempio n. 10
0
class LightMaps(QWidget):
    def __init__(self, parent=None):
        super(LightMaps, self).__init__(parent)

        self.pressed = False
        self.snapped = False
        self.zoomed = False
        self.invert = False
        self._normalMap = SlippyMap(self)
        self._largeMap = SlippyMap(self)
        self.pressPos = QPoint()
        self.dragPos = QPoint()
        self.tapTimer = QBasicTimer()
        self.zoomPixmap = QPixmap()
        self.maskPixmap = QPixmap()
        self._normalMap.updated.connect(self.updateMap)
        self._largeMap.updated.connect(self.update)

    def setCenter(self, lat, lng):
        self._normalMap.latitude = lat
        self._normalMap.longitude = lng
        self._normalMap.invalidate()
        self._largeMap.invalidate()

    # slots
    def toggleNightMode(self):
        self.invert = not self.invert
        self.update()

    def updateMap(self, r):
        self.update(r)

    def activateZoom(self):
        self.zoomed = True
        self.tapTimer.stop()
        self._largeMap.zoom = self._normalMap.zoom + 1
        self._largeMap.width = self._normalMap.width * 2
        self._largeMap.height = self._normalMap.height * 2
        self._largeMap.latitude = self._normalMap.latitude
        self._largeMap.longitude = self._normalMap.longitude
        self._largeMap.invalidate()
        self.update()

    def resizeEvent(self, event):
        self._normalMap.width = self.width()
        self._normalMap.height = self.height()
        self._normalMap.invalidate()
        self._largeMap.width = self._normalMap.width * 2
        self._largeMap.height = self._normalMap.height * 2
        self._largeMap.invalidate()

    def paintEvent(self, event):
        p = QPainter()
        p.begin(self)
        self._normalMap.render(p, event.rect())
        p.setPen(Qt.black)
        # p.drawText(self.rect(), Qt.AlignBottom | Qt.TextWordWrap, "Map data CCBYSA 2009 OpenStreetMap.org contributors")
        p.end()

        if self.zoomed:
            dim = min(self.width(), self.height())
            magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3)
            radius = magnifierSize / 2
            ring = radius - 15
            box = QSize(magnifierSize, magnifierSize)

            # reupdate our mask
            if self.maskPixmap.size() != box:
                self.maskPixmap = QPixmap(box)
                self.maskPixmap.fill(Qt.transparent)
                g = QRadialGradient()
                g.setCenter(radius, radius)
                g.setFocalPoint(radius, radius)
                g.setRadius(radius)
                g.setColorAt(1.0, QColor(255, 255, 255, 0))
                g.setColorAt(0.5, QColor(128, 128, 128, 255))
                mask = QPainter(self.maskPixmap)
                mask.setRenderHint(QPainter.Antialiasing)
                mask.setCompositionMode(QPainter.CompositionMode_Source)
                mask.setBrush(g)
                mask.setPen(Qt.NoPen)
                mask.drawRect(self.maskPixmap.rect())
                mask.setBrush(QColor(Qt.transparent))
                mask.drawEllipse(g.center(), ring, ring)
                mask.end()

            center = self.dragPos - QPoint(0, radius)
            center += QPoint(0, radius / 2)
            corner = center - QPoint(radius, radius)
            xy = center * 2 - QPoint(radius, radius)
            # only set the dimension to the magnified portion
            if self.zoomPixmap.size() != box:
                self.zoomPixmap = QPixmap(box)
                self.zoomPixmap.fill(Qt.lightGray)

            if True:
                p = QPainter(self.zoomPixmap)
                p.translate(-xy)
                self._largeMap.render(p, QRect(xy, box))
                p.end()

            clipPath = QPainterPath()
            clipPath.addEllipse(QPointF(center), ring, ring)
            p = QPainter(self)
            p.setRenderHint(QPainter.Antialiasing)
            p.setClipPath(clipPath)
            p.drawPixmap(corner, self.zoomPixmap)
            p.setClipping(False)
            p.drawPixmap(corner, self.maskPixmap)
            p.setPen(Qt.gray)
            p.drawPath(clipPath)

        if self.invert:
            p = QPainter(self)
            p.setCompositionMode(QPainter.CompositionMode_Difference)
            p.fillRect(event.rect(), Qt.white)
            p.end()

    def timerEvent(self, event):
        if not self.zoomed:
            self.activateZoom()

        self.update()

    def mousePressEvent(self, event):
        if event.buttons() != Qt.LeftButton:
            return

        self.pressed = self.snapped = True
        self.pressPos = self.dragPos = event.pos()
        self.tapTimer.stop()
        self.tapTimer.start(HOLD_TIME, self)

    def mouseMoveEvent(self, event):
        if not event.buttons():
            return

        if not self.zoomed:
            if not self.pressed or not self.snapped:
                delta = event.pos() - self.pressPos
                self.pressPos = event.pos()
                self._normalMap.pan(delta)
                return
            else:
                threshold = 10
                delta = event.pos() - self.pressPos
                if self.snapped:
                    self.snapped &= delta.x() < threshold
                    self.snapped &= delta.y() < threshold
                    self.snapped &= delta.x() > -threshold
                    self.snapped &= delta.y() > -threshold

                if not self.snapped:
                    self.tapTimer.stop()

        else:
            self.dragPos = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):
        self.zoomed = False
        self.update()

    def keyPressEvent(self, event):
        if not self.zoomed:
            if event.key() == Qt.Key_Left:
                self._normalMap.pan(QPoint(20, 0))
            if event.key() == Qt.Key_Right:
                self._normalMap.pan(QPoint(-20, 0))
            if event.key() == Qt.Key_Up:
                self._normalMap.pan(QPoint(0, 20))
            if event.key() == Qt.Key_Down:
                self._normalMap.pan(QPoint(0, -20))
            if event.key() == Qt.Key_Z or event.key() == Qt.Key_Select:
                self.dragPos = QPoint(self.width() / 2, self.height() / 2)
                self.activateZoom()
        else:
            if event.key() == Qt.Key_Z or event.key() == Qt.Key_Select:
                self.zoomed = False
                self.update()

            delta = QPoint(0, 0)
            if event.key() == Qt.Key_Left:
                delta = QPoint(-15, 0)
            if event.key() == Qt.Key_Right:
                delta = QPoint(15, 0)
            if event.key() == Qt.Key_Up:
                delta = QPoint(0, -15)
            if event.key() == Qt.Key_Down:
                delta = QPoint(0, 15)
            if delta != QPoint(0, 0):
                self.dragPos += delta
                self.update()
Esempio n. 11
0
class MineSweeperWindow(QMainWindow):
    def __init__(self, mode):
        super().__init__()
        self.ms = mode
        self.init_ui()
        self.set_menu()

    def init_ui(self):
        """初始化游戏界面"""
        # 1.确定游戏界面的标题,大小和背景颜色
        self.setObjectName('MainWindow')
        self.setWindowTitle('扫雷')
        self.setWindowIcon(QIcon(':/minesweeper.ico'))
        self.setFixedSize(50 * self.ms.length + 100, 50 * self.ms.width + 180)
        self.setStyleSheet('#MainWindow{background-color: #f6edd2}')
        self.remain_boom = QLCDNumber(2, self)
        self.remain_boom.move(50, 50)
        self.remain_boom.setFixedSize(60, 50)
        self.remain_boom.setStyleSheet(
            "border: 2px solid blue; color: red; background: black;")
        self.remain_boom.display(
            '{:>02d}'.format(self.ms.b_num if self.ms.b_num >= 0 else 0))
        self.timer = QBasicTimer()
        self.second = 0
        self.time = QLCDNumber(3, self)
        self.time.move(50 * self.ms.length - 40, 50)
        self.time.setFixedSize(90, 50)
        self.time.setStyleSheet(
            "border: 2px solid blue; color: red; background: black;")
        self.time.display('{:>03d}'.format(self.second))
        self.btn = QPushButton(self)
        self.btn.move(25 * self.ms.length + 20, 50)
        self.btn.setFixedSize(50, 50)
        self.btn.setIcon(QIcon(':/普通.png'))
        self.btn.setIconSize(QSize(45, 45))
        self.btn.setStyleSheet('QPushButton{border:None}')
        self.btn.clicked.connect(self.restart)
        self.over_signal = 0
        self.rank = sqlite3.connect('rank.db')
        self.c = self.rank.cursor()

    def set_menu(self):
        bar = self.menuBar()
        game = bar.addMenu('游戏(&G)')
        more_info = bar.addMenu('更多(&M)')

        new_game = QAction('新游戏(&N)', self)
        new_game.setShortcut('Ctrl+N')
        new_game.triggered.connect(self.start)
        game.addAction(new_game)
        restart = QAction('重玩(&R)', self)
        restart.setShortcut('Ctrl+R')
        restart.triggered.connect(self.restart)
        game.addAction(restart)
        game.addSeparator()
        self.modes = QActionGroup(self)
        self.easy = QAction('简单(E)', self)
        self.easy.setCheckable(True)
        game.addAction(self.modes.addAction(self.easy))
        self.medium = QAction('中等(M)', self)
        self.medium.setCheckable(True)
        game.addAction(self.modes.addAction(self.medium))
        self.hard = QAction('困难(H)', self)
        self.hard.setCheckable(True)
        game.addAction(self.modes.addAction(self.hard))
        self.modes.triggered.connect(
            lambda: self.set_mode(self.modes.checkedAction()))
        if isinstance(self.ms, EasyMode):
            self.easy.setChecked(True)
        elif isinstance(self.ms, MediumMode):
            self.medium.setChecked(True)
        elif isinstance(self.ms, HardMode):
            self.hard.setChecked(True)

        rank = QAction('排行耪(&R)', self)
        rank.triggered.connect(self.show_rank)
        more_info.addAction(rank)

    def paintEvent(self, e):
        """绘制游戏内容"""
        qp = QPainter()

        def draw_map():
            """绘制版面"""
            # background = QPixmap(':/背景2.png')
            # qp.drawPixmap(self.rect(), background)
            # qp.setBrush(QColor('#e8ff9d'))
            # qp.drawRect(50, 130, 50 * self.ms.length, 50 * self.ms.width)
            for x in range(0, self.ms.length, 2):
                for y in range(0, self.ms.width, 2):
                    qp.setBrush(QColor('#007a15'))
                    qp.drawRect(50 * (x + 1), 50 * (y + 1) + 80, 50, 50)
                for y in range(1, self.ms.width, 2):
                    qp.setBrush(QColor('#00701c'))
                    qp.drawRect(50 * (x + 1), 50 * (y + 1) + 80, 50, 50)
            for x in range(1, self.ms.length, 2):
                for y in range(0, self.ms.width, 2):
                    qp.setBrush(QColor('#00701c'))
                    qp.drawRect(50 * (x + 1), 50 * (y + 1) + 80, 50, 50)
                for y in range(1, self.ms.width, 2):
                    qp.setBrush(QColor('#007a15'))
                    qp.drawRect(50 * (x + 1), 50 * (y + 1) + 80, 50, 50)
            # qp.setPen(QPen(QColor(111, 108, 108), 2, Qt.SolidLine))
            # for x in range(self.ms.length + 1):
            #     qp.drawLine(50 * (x + 1), 130, 50 * (x + 1), 50 * self.ms.width + 130)
            # for y in range(self.ms.width + 1):
            #     qp.drawLine(50, 50 * (y + 1) + 80, 50 * self.ms.length + 50, 50 * (y + 1) + 80)

        def draw_blanks():
            qp.setBrush(QColor('#f4f4f4'))
            for x in range(self.ms.length):
                for y in range(self.ms.width):
                    if isinstance(self.ms.g_map[y][x], str):
                        if self.ms.g_map[y][x] == '0$' or self.ms.g_map[y][
                                x] == '1$':
                            # qp.setPen(QPen(QColor(219, 58, 58), 1, Qt.SolidLine))
                            # qp.setFont(QFont('Kai', 15))
                            flag = QPixmap(':/雷旗.png').scaled(50, 50)
                            qp.drawPixmap(
                                QRect(50 * (x + 1), 50 * (y + 1) + 80, 50, 50),
                                flag)
                            # qp.drawText(50 * (x + 1) + 18, 50 * (y + 1) + 115, '$')
                            continue
                        qp.setPen(QPen(QColor('black'), 1, Qt.SolidLine))
                        qp.setFont(QFont('Kai', 15))
                        qp.drawRect(50 * (x + 1), 50 * (y + 1) + 80, 50, 50)
                        if self.ms.g_map[y][x] == '0':
                            continue
                        if self.ms.g_map[y][x] == '*':
                            flag = QPixmap(':/土豆雷.png').scaled(50, 50)
                            qp.drawPixmap(
                                QRect(50 * (x + 1), 50 * (y + 1) + 80, 50, 50),
                                flag)
                            continue
                        qp.setPen(QPen(QColor('black'), 5, Qt.SolidLine))
                        qp.drawText(50 * (x + 1) + 18, 50 * (y + 1) + 115,
                                    '{}'.format(self.ms.g_map[y][x]))

        qp.begin(self)
        draw_map()
        draw_blanks()
        qp.end()

    def mousePressEvent(self, e):
        """根据鼠标的动作,确定落子位置"""
        if self.over_signal == 1:
            return
        if e.button() in (Qt.LeftButton, Qt.RightButton):
            mouse_x = e.windowPos().x()
            mouse_y = e.windowPos().y()
            if 50 <= mouse_x <= 50 * self.ms.length + 50 and 130 <= mouse_y <= 50 * self.ms.width + 130:
                if self.ms.step == 0:
                    self.timer.start(1000, self)
                    self.tic = time_ns()
                game_x = int(mouse_x // 50) - 1
                game_y = int((mouse_y - 80) // 50) - 1
            else:
                return
            if e.buttons() == Qt.LeftButton | Qt.RightButton:
                self.ms.click_around(game_x, game_y)
            elif e.buttons() == Qt.LeftButton:
                self.ms.click(game_x, game_y)
            else:
                self.ms.mark_mine(game_x, game_y)
        if self.ms.boom:
            self.timer.stop()
            self.btn.setIcon(QIcon(':/哭脸.png'))
            self.btn.setIconSize(QSize(45, 45))
            self.repaint(0, 0, 50 * self.ms.length + 100,
                         50 * self.ms.width + 180)
            self.over_signal = 1
            return
        elif self.ms.game_judge():
            self.timer.stop()
            self.toc = time_ns()
            self.btn.setIconSize(QSize(45, 45))
            self.btn.setIcon(QIcon(':/笑脸.png'))
            self.repaint(0, 0, 50 * self.ms.length + 100,
                         50 * self.ms.width + 180)
            self.check_rank()
            self.over_signal = 1
            return
        self.repaint(0, 0, 50 * self.ms.length + 100, 50 * self.ms.width + 180)
        self.remain_boom.display(
            '{:>02d}'.format(self.ms.b_num if self.ms.b_num >= 0 else 0))

    def timerEvent(self, e) -> None:
        self.second += 1
        self.time.display('{:>03d}'.format(self.second))

    def set_mode(self, action: QAction):
        if action == self.easy:
            self.close()
            self.msw = MineSweeperWindow(EasyMode())
            self.msw.show()
        elif action == self.medium:
            self.close()
            self.msw = MineSweeperWindow(MediumMode())
            self.msw.show()
        elif action == self.hard:
            self.close()
            self.msw = MineSweeperWindow(HardMode())
            self.msw.show()

    def show_rank(self):
        self.sk = ShowRank()
        self.sk.show()

    def start(self):
        self.close()
        self.a = Start()
        self.a.show()

    def restart(self):
        self.ms.refresh()
        self.repaint()
        self.btn.setIcon(QIcon(':/普通.png'))
        self.remain_boom.display(
            '{:>02d}'.format(self.ms.b_num if self.ms.b_num >= 0 else 0))
        self.second = 0
        self.timer.stop()
        self.time.display('{:>03d}'.format(self.second))
        self.over_signal = 0

    def check_rank(self):
        a_num = (self.toc - self.tic) / 10**9
        out = subprocess.check_output("whoami").decode("gbk")
        name = re.search(r"\\(.+)\r\n", out)
        a_user = name.group(1)
        for i in range(5, 0, -1):
            if isinstance(self.ms, EasyMode):
                mode = "Easy"
            elif isinstance(self.ms, MediumMode):
                mode = "Medium"
            elif isinstance(self.ms, HardMode):
                mode = "Hard"
            else:
                return
            self.c.execute("SELECT * FROM {} WHERE id=?;".format(mode), (i, ))
            feedback = self.c.fetchone()
            if i == 5:
                if (not feedback[2]) or (feedback[2] > a_num):
                    a_user, _ = QInputDialog.getText(self,
                                                     "用户名",
                                                     "请输入用户名:",
                                                     QLineEdit.Normal,
                                                     text=a_user)
                    self.c.execute(
                        "UPDATE {} SET user=?, time=? WHERE id=?;".format(
                            mode), (a_user, a_num, i))
                    self.rank.commit()
                    continue
                else:
                    return
            else:
                if (not feedback[2]) or (feedback[2] > a_num):
                    self.c.execute(
                        "UPDATE {0} "
                        "SET user = (SELECT user FROM {0} WHERE id=?), "
                        "time = (SELECT time FROM {0} WHERE id=?)"
                        "WHERE id=? ;".format(mode), (i, i, i + 1))
                    self.c.execute(
                        "UPDATE {} SET user=?, time=? WHERE id=? ;".format(
                            mode), (a_user, a_num, i))
                    self.rank.commit()
                else:
                    return

    def closeEvent(self, e):
        self.rank.commit()
        self.rank.close()