예제 #1
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setGeometry(30, 40, 200, 25)
 
        self.btn = QPushButton('Start', self)
        self.btn.move(30, 80)
        self.btn.clicked.connect(self.doAction)
 
        self.timer = QBasicTimer()
        self.step = 0
 
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QProgressBar')
        self.show()
 
    def timerEvent(self, QTimerEvent):
        if self.step >= 100:
            self.timer.stop()
            self.btn.setText('Finished')
            return
        self.step += 1
        self.progress_bar.setValue(self.step)
 
    def doAction(self):
        if self.timer.isActive():
            self.timer.stop()
            self.btn.setText('Start')
        else:
            self.timer.start(100, self)
            self.btn.setText('Stop')
예제 #2
0
파일: configurator.py 프로젝트: np/MadCatz
class T_window(QWidget):
    def __init__(self):
        super().__init__()
        self.tabs = QTabWidget()
        self.com = T_communication()
        self.pbar = QProgressBar()
        self.pbar.setFormat("Battery : %p%")
        self.grid = QGridLayout()

        self.setLayout(self.grid)
        self.grid.addWidget(self.pbar)
        self.grid.addWidget(self.tabs)

        self.dpi = T_dpi()
        self.com.getDpi(self.dpi)
        self.dpi.dataHasBeenSent()
        self.t = []
        for i in range(0, 4):
            self.t.append(T_tab(i, self.dpi, self.com))
            self.tabs.addTab(self.t[i], "Mode " + str(i + 1))

        self.data = T_data(self.pbar, self.tabs, self.dpi, self.com)
        for i in range(0, 4):
            self.t[i].sendButton.clicked.connect(self.data.sendDpi)
            self.t[i].resetButton.clicked.connect(self.com.resetDpi)
        self.timer = QBasicTimer()
        self.timer.start(100, self.data)
        self.tabs.currentChanged.connect(self.com.sendMode)
예제 #3
0
class Marquee(QLabel):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.right_to_left_direction = True
        self.initUI()
        self.timer = QBasicTimer()
        self.timer.start(80, self)

    def initUI(self):
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setText("Hello World! ")
        self.setFont(QFont(None, 50, QFont.Bold))
        # make more irritating for the authenticity with <marquee> element
        self.setStyleSheet("QLabel {color: cyan; }")

    def timerEvent(self, event):
        i = 1 if self.right_to_left_direction else -1
        self.setText(self.text()[i:] + self.text()[:i])  # rotate

    def mouseReleaseEvent(self, event):  # change direction on mouse release
        self.right_to_left_direction = not self.right_to_left_direction

    def keyPressEvent(self, event):  # exit on Esc
        if event.key() == Qt.Key_Escape:
            self.close()
예제 #4
0
class AutoSaver(QObject):
    """
    Class implementing the auto saver.
    """
    AUTOSAVE_IN = 1000 * 3
    MAXWAIT = 1000 * 15
    
    def __init__(self, parent, save):
        """
        Constructor
        
        @param parent reference to the parent object (QObject)
        @param save slot to be called to perform the save operation
        @exception RuntimeError raised, if no parent is given
        """
        super(AutoSaver, self).__init__(parent)
        
        if parent is None:
            raise RuntimeError("AutoSaver: parent must not be None.")
        
        self.__save = save
        
        self.__timer = QBasicTimer()
        self.__firstChange = QTime()
    
    def changeOccurred(self):
        """
        Public slot handling a change.
        """
        if self.__firstChange.isNull():
            self.__firstChange.start()
        
        if self.__firstChange.elapsed() > self.MAXWAIT:
            self.saveIfNeccessary()
        else:
            self.__timer.start(self.AUTOSAVE_IN, self)
    
    def timerEvent(self, evt):
        """
        Protected method handling timer events.
        
        @param evt reference to the timer event (QTimerEvent)
        """
        if evt.timerId() == self.__timer.timerId():
            self.saveIfNeccessary()
        else:
            super(AutoSaver, self).timerEvent(evt)
    
    def saveIfNeccessary(self):
        """
        Public method to activate the save operation.
        """
        if not self.__timer.isActive():
            return
        
        self.__timer.stop()
        self.__firstChange = QTime()
        self.__save()
class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):      

        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)

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

        # タイマー
        self.timer = QBasicTimer()
        self.step = 0
        
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QProgressBar')
        self.show()
        
        
    def timerEvent(self, e):
        # カウントが100に達すると終了
        if self.step >= 100:
            self.timer.stop()
            self.btn.setText('Finished')
            return
    
        # 呼ばれるたび1ずつ増やす
        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:
            # (timeout[ms], イベントの受取先)
            # timeoutで指定した時間間隔でシグナルが飛ぶ模様
            self.timer.start(1000, self)
            self.btn.setText('Stop')
예제 #6
0
class WigglyLabel(object):

    def __init__(self, clazz):
        self.clazz = clazz
        # clazz.setBackgroundRole(QPalette.Midlight)
        # clazz.setAutoFillBackground(True)

        setattr(clazz, "paintEvent", self.paintEvent)
        setattr(clazz, "timerEvent", self.timerEvent)

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

        self.timer = QBasicTimer()

        self.step = 0;
        self.timer.start(60, self.clazz)

    def __del__(self):
        self.timer.stop()

    def getText(self):
        return self.clazz.text()

    def paintEvent(self, event):
        # 上下跳动
        # sineTable = (0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38)

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

        painter = QPainter(self.clazz)

        for i, ch in enumerate(self.getText()):
            index = (self.step + i) % 16
            color.setHsv((15 - index) * 16, 255, 191)
            painter.setPen(color)
            # 上下跳动
            # painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), ch)
            painter.drawText(x, y , ch)
            x += metrics.width(ch)

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            self.step += 1
            self.clazz.update()
        else:
            super(WigglyLabel, self).timerEvent(event)
예제 #7
0
class setupWidget(QWidget):

	def __init__(self,parent_):
		super(setupWidget,self).__init__(parent_)
		self.parent_=parent_
		self.initUI()

	def initUI(self):
		self.pbar = QProgressBar(self)
		self.pbar.setObjectName('pbar')
		self.pbar.setTextVisible(True)
		self.pbar.setFormat('Configuring...')

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

		pixmap=QPixmap(':/Assets/moodly.gif')
		lbl=QLabel(self)
		lbl.setPixmap(pixmap)

		hbox1=QHBoxLayout()
		hbox1.addStretch(1)
		hbox1.addWidget(lbl)
		hbox1.addStretch(1)

		hbox2=QHBoxLayout()
		hbox2.addStretch(1)
		hbox2.addWidget(self.pbar)
		hbox2.addStretch(1)

		vbox=QVBoxLayout()
		vbox.addStretch(8)
		vbox.addLayout(hbox1)
		vbox.addStretch(1)
		vbox.addLayout(hbox2)
		vbox.addStretch(8)

		self.setLayout(vbox)
		self.callTimer()

	def timerEvent(self,e):
		if self.step>=100:
			self.step=0
		self.step=self.step+1
		self.pbar.setValue(self.step)

	def callTimer(self):
		 self.timer.start(100, self)
예제 #8
0
class MyQt(QWidget):
    def __init__(self):
        super(MyQt, self).__init__()
        self.initUI()

    def initUI(self):
        # 构建一个进度条
        self.pbar = QProgressBar(self)
        # 从左上角30-50的界面,显示一个200*25的界面
        self.pbar.setGeometry(30, 50, 200, 25)  # 设置进度条的位置
        # 设置开始按钮
        self.btn = QPushButton('开始', self)
        self.btn.move(50, 90)  # 按钮移动的位置
        # 点击按钮
        # 信号函数不能加括号
        self.btn.clicked.connect(self.doAction)


        # 构建一个计时器
        self.timer = QBasicTimer()
        # 计数
        self.step = 0
        self.setGeometry(300,300,280,170)
        self.setWindowTitle('我是进度条')
        self.setWindowIcon(QIcon('1.jpg'))

        self.show()

    def doAction(self):
        # 判断是否处于激活状态
        if self.timer.isActive():
            self.timer.stop()
            self.btn.setText('开始')
        else:
            self.timer.start(100,self)
            self.btn.setText('停止')
    def timerEvent(self, *args, **kwargs):
        if self.step>=100:
            # 停止进度条
            self.timer.stop()
            self.btn.setText('完成')
            return
        self.step+=1
        # 把进度条每次充值的值赋给进图条
        self.pbar.setValue(self.step)
예제 #9
0
class WigglyWidget(QWidget):
    def __init__(self, parent=None):
        super(WigglyWidget, self).__init__(parent)

        self.setBackgroundRole(QPalette.Midlight)
        self.setAutoFillBackground(True)

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

        self.timer = QBasicTimer()
        self.text = ''

        self.step = 0;
        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.width(self.text)) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        color = QColor()

        painter = QPainter(self)

        for i, ch in enumerate(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), ch)
            x += metrics.width(ch)

    def setText(self, newText):
        self.text = newText

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            self.step += 1
            self.update()
        else:
            super(WigglyWidget, self).timerEvent(event)
예제 #10
0
파일: MainWindow.py 프로젝트: zwdnet/liquid
class LiquidBox(QWidget):
    # 模拟流体力学程序,盛着液体的盒子
    def __init__(self):
        super().__init__()
        self.speed = 100  #重绘速度1s
        self.WindowSize = 50
        self.timer = QBasicTimer()
        self.sim = sm.Stimulator(self.WindowSize)
        self.initUI()

    def initUI(self):
        self.setGeometry(200, 200, 600, 600)
        self.setFixedSize(400, 400)
        self.setWindowTitle("流体力学模拟程序")
        self.timer.start(self.speed, self)
        self.show()

    #处理计时器消息
    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            self.update()
        else:
            super().timerEvent(event)

    #处理重绘消息
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        self.Draw(qp)
        qp.end()

    #具体绘图函数
    def Draw(self, qp):
        qp.setPen(Qt.blue)
        points = self.sim.step()
        for i in range(len(points)):
            qp.drawPoint(int(points[i][0]), int(points[i][1]))
예제 #11
0
class MouseFollower(QWidget):
	def __init__(self, *args):
		super(MouseFollower, self).__init__(*args)

		self.following = False
		self.grabbing = False
		self.cursorTimer = QBasicTimer()

	def isGrabbing(self):
		return self.grabbing

	def isFollowing(self):
		return self.following

	mouseMoved = Signal(QPoint)
	clickWhileGrabbed = Signal()

	@Slot()
	def toggleGrab(self):
		refollow = self.following
		
		if refollow:
			self.endFollow()
		self.grabbing = not self.grabbing
		
		if refollow:
			self.startFollow()

	def toggleFollow(self):
		if self.following:
			self.endFollow()
		else:
			self.startFollow()

	@Slot()
	def startFollow(self):
		if not self.grabbing:
			self.cursorTimer.start(100, self)
		else:
			self.setMouseTracking(True)
			self.grabMouse()
		self.following = True

	@Slot()
	def endFollow(self):
		if not self.grabbing:
			self.cursorTimer.stop()
		else:
			self.releaseMouse()
		self.following = False

	def timerEvent(self, ev):
		if ev.timerId() == self.cursorTimer.timerId():
			self.mouseMoved.emit(QCursor.pos())
		else:
			super(MouseFollower, self).timerEvent(ev)

	def mouseMoveEvent(self, ev):
		self.mouseMoved.emit(QCursor.pos())
		return super(MouseFollower, self).mouseMoveEvent(ev)

	def mousePressEvent(self, ev):
		if self.grabbing:
			self.clickWhileGrabbed.emit()
		return super(MouseFollower, self).mousePressEvent(ev)
예제 #12
0
class DedeNimeur(QMainWindow):
    def __init__(self):
        super(DedeNimeur, self).__init__()
        self.statusBar()

        self.size, self.height, self.width, self.mines = 30, 10, 10, 10
        self.lcd = QLCDNumber()
        self.lcd.setFixedSize(300, 60)
        self.board = Board(self.height, self.width, self.mines, self.size)
        self.timer = QBasicTimer()
        self.real_timer = QElapsedTimer()

        vbox = QVBoxLayout()
        vbox.addWidget(self.lcd)
        vbox.addWidget(self.board)

        central = QWidget()
        central.setLayout(vbox)
        self.setCentralWidget(central)

        start = QAction('Start', self)
        start.setStatusTip('Start')
        start.setShortcut('Ctrl+N')
        start.triggered.connect(self.init)

        exit = QAction('Exit', self)
        exit.setStatusTip('Exit')
        exit.setShortcut('Ctrl+Q')
        exit.triggered.connect(qApp.quit)

        height = QAction('Height', self)
        height.setStatusTip('Set board width')
        height.triggered.connect(self.set_height)
        width = QAction('Width', self)
        width.setStatusTip('Set board height')
        width.triggered.connect(self.set_width)
        mines = QAction('Mines', self)
        mines.setStatusTip('Set board mines')
        mines.triggered.connect(self.set_mines)
        size = QAction('Size', self)
        size.setStatusTip('Set button size')
        size.triggered.connect(self.set_size)

        toolbar = self.addToolBar('Toolbar')
        toolbar.addAction(start)
        toolbar.addAction(width)
        toolbar.addAction(height)
        toolbar.addAction(mines)
        toolbar.addAction(size)
        toolbar.addAction(exit)

        self.setWindowTitle(u'DédéNimeur')
        self.show()

    def init(self):
        if self.mines < self.height * self.width:
            self.board.height = self.height
            self.board.width = self.width
            self.board.mines = self.mines
            self.board.size = self.size
            self.board.init()
        else:
            QMessageBox.question(self, 'NOPE', u"Va falloir spécifier un truc cohérent…", QMessageBox.Ok)

    def set_height(self):
        text, ok = QInputDialog.getText(self, 'Settings', 'height')
        if ok:
            self.height = int(text)
            self.init()

    def set_width(self):
        text, ok = QInputDialog.getText(self, 'Settings', 'width')
        if ok:
            self.width = int(text)
            self.init()

    def set_mines(self):
        text, ok = QInputDialog.getText(self, 'Settings', 'mines')
        if ok:
            self.mines = int(text)
            self.init()

    def set_size(self):
        text, ok = QInputDialog.getText(self, 'Settings', 'size')
        if ok:
            self.size = int(text)
            self.init()

    def start_timers(self):
        self.timer.start(100, self)
        self.real_timer.start()
        self.lcd.display(int(self.real_timer.elapsed() / 1000))

    def stop_timers(self):
        self.timer.stop()
        return self.real_timer.elapsed()

    def timerEvent(self, e):
        self.lcd.display(int(self.real_timer.elapsed() / 1000))
예제 #13
0
class HAdjustmentBar(QWidget):
    valueChanged = pyqtSignal(int)
    def __init__(self, parent=None):
        super(HAdjustmentBar, self).__init__(parent)
        self.value = 50
        self.step = 1
        self.hi_value = 100
        self.low_value = 50
        self.timer_value = 25
        self.texttemplate = 'Value =  %s'
        self.timer = QBasicTimer()
        self.showToggleButton = True
        self.showSettingMenu = True
        self.bar = LabeledBar()
        #self.bar.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
        # black magic class patching
        # so calling these functions actually calls the self.bar's functions.
        self.minimum = self.bar.minimum
        self.maximum = self.bar.maximum

    def buildWidget(self):
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0,0,0,0)
        SettingMenu = QMenu()
        exitButton = QAction(QIcon('exit24.png'), 'Set As High', self)
        exitButton.triggered.connect(self.setHigh)
        SettingMenu.addAction(exitButton)
        setlowButton = QAction(QIcon('exit24.png'), 'Set As Low', self)
        setlowButton.triggered.connect(self.setLow)
        SettingMenu.addAction(setlowButton)

        self.tb_down = QToolButton()
        self.tb_down.pressed.connect(self.on_click_down)
        self.tb_down.released.connect(self.on_released)
        self.tb_down.setArrowType(Qt.LeftArrow)

        self.tb_up = QToolButton()
        self.tb_up.pressed.connect(self.on_click_up)
        self.tb_up.released.connect(self.on_released)
        self.tb_up.setArrowType(Qt.RightArrow)

        if self.showToggleButton:
            tb_set = QToolButton()
            tb_set.clicked.connect(self.on_click_set_value)
            tb_set.setText('<>')
            if self.showSettingMenu:
                tb_set.setMenu(SettingMenu)
                tb_set.setPopupMode(QToolButton.DelayedPopup)

        layout.addWidget(self.tb_down)
        layout.addWidget(self.bar)
        layout.addWidget(self.tb_up)
        if self.showToggleButton:
            layout.addWidget(tb_set)
        layout.setSpacing(0)

    def on_click_up(self):
        self.timer.start(self.timer_value, self)
        self.value += self.step
        self._setValue()

    def on_click_down(self):
        self.timer.start(self.timer_value, self)
        self.value -= self.step
        self._setValue()
    def on_released(self):
        self.timer.stop()

    def on_click_set_value(self):
        if self.value == self.hi_value:
            self.value = self.low_value
        else:
            self.value = self.hi_value
        self._setValue()

    def timerEvent(self, e):
        if self.value < self.maximum() and self.value > self.minimum():
            if self.tb_down.isDown():
                self.value -= self.step
            else:
                self.value += self.step
            self._setValue()
        else:
            self.timer.stop()

    def _setValue(self):
        if self.value < self.minimum():self. value = self.minimum()
        if self.value > self.maximum(): self.value = self.maximum()
        self.valueChanged.emit(self.value)

    def setValue(self, value):
        if value < self.minimum(): value = self.minimum()
        if value > self.maximum(): value = self.maximum()
        self.value = int(value)
        tmpl = lambda s: self.texttemplate % s
        try:
            self.bar.text = tmpl(int(value))
        except:
            self.bar.text = self.texttemplate
        self.bar.setValue(int(value))
        self.bar.update()

    def setHigh(self):
        self.hi_value = self.value

    def setLow(self):
        self.low_value = self.value

    def setMaximum(self, data):
        if data < self.hi_value:
            self.hi_value = data
        self.bar.setMaximum(data)

    def setMinimum(self, data):
        if data > self.low_value:
            self.low_value = data
        self.bar.setMinimum(data)
예제 #14
0
class Interface(QWidget):
    # TODO
    # 重载keypressevent,实现按q键时退出

    def __init__(self):
        super().__init__()
        self.captionSize = 20
        self.captionFontFamily = "STHeitiTC-Light"

        # 数据
        self.nsize = 12
        self.arr = numpy.zeros(shape=self.nsize, dtype=float)

        # 初始化client,开启线程
        self.client = socket(AF_INET, SOCK_STREAM)
        self.client.connect(('localhost', 25000))
        self.t = threading.Thread(target=self.func)
        self.t.start()

        self.initUI()

    def func(self):
        while (1):
            recv_into(self.arr, self.client)

    def initUI(self):
        self.timer = QBasicTimer()

        guiBox = QHBoxLayout()
        generalMessageBox = QVBoxLayout()
        cardsBox = QVBoxLayout()
        tabs = QTabWidget()
        cardsBox.addWidget(tabs)

        guiBox.addLayout(generalMessageBox)
        guiBox.addLayout(cardsBox)

        #训练进度
        self.trainCaptionLabel = QLabel()
        self.trainCaptionLabel.setText("训练进度")

        self.epochLabel = QLabel()
        self.epochLabel.setText("Epoch /")

        self.captionBox = QHBoxLayout()
        self.captionBox.addWidget(self.trainCaptionLabel)
        self.captionBox.addStretch(1)
        self.captionBox.addWidget(self.epochLabel)

        self.trainProgressBar = QProgressBar()
        self.trainProgressBar.setValue(0)

        self.trainProgressLabel = QLabel()
        self.trainProgressLabel.setText("_ / _")

        self.trainProgressBox = QHBoxLayout()
        self.trainProgressBox.addWidget(self.trainProgressBar)
        self.trainProgressBox.addWidget(self.trainProgressLabel)

        #训练集表现
        self.trainPerformanceBox = QVBoxLayout()
        self.trainPerformanceCaptionLabel = QLabel()
        self.trainPerformanceCaptionLabel.setText("训练集表现")
        self.trainPerformanceCaptionLabel.setFont(
            QFont(self.captionFontFamily, self.captionSize, QFont.Bold))

        self.trainLossLabel = QLabel()
        self.trainLossLabel.setText("Loss    /")

        self.trainTop1AccLabel = QLabel()
        self.trainTop1AccLabel.setText("Acc@1 /")

        self.trainTop5AccLabel = QLabel()
        self.trainTop5AccLabel.setText("Acc@5 /")

        self.trainPerformanceValueBox = QHBoxLayout()
        self.trainPerformanceValueBox.addWidget(self.trainTop1AccLabel)
        self.trainPerformanceValueBox.addStretch(1)
        self.trainPerformanceValueBox.addWidget(self.trainTop5AccLabel)

        self.trainPerformanceBox.addWidget(self.trainPerformanceCaptionLabel)
        self.trainPerformanceBox.addWidget(self.trainLossLabel)
        self.trainPerformanceBox.addLayout(self.trainPerformanceValueBox)

        #测试集表现
        self.evalPerformanceCaptionLabel = QLabel()
        self.evalPerformanceCaptionLabel.setText("测试集表现")
        self.evalPerformanceCaptionLabel.setFont(
            QFont(self.captionFontFamily, self.captionSize, QFont.Bold))

        self.evalPerformaceTabs = QTabWidget()
        self.evalBestPerformanceTab = QWidget()
        self.evalPerformanceBox = QVBoxLayout(self.evalBestPerformanceTab)
        self.evalLastPerformanceTab = QWidget()
        self.evalLastPerformanceBox = QVBoxLayout(self.evalLastPerformanceTab)

        self.evalPerformaceTabs.addTab(self.evalBestPerformanceTab,
                                       "Best result")
        self.evalPerformaceTabs.addTab(self.evalLastPerformanceTab,
                                       "Last result")

        #测试集最佳表现
        self.evalLossLabel = QLabel()
        self.evalLossLabel.setText("Loss")
        self.evalLossValueLabel = QLabel()
        self.evalLossValueLabel.setText("/")
        self.evalLossBox = QHBoxLayout()
        self.evalLossBox.addWidget(self.evalLossLabel)
        self.evalLossBox.addStretch(1)
        self.evalLossBox.addWidget(self.evalLossValueLabel)

        self.evalTop1AccLabel = QLabel()
        self.evalTop1AccLabel.setText("Best Top-1 Acc")
        self.evalTop1AccValueLabel = QLabel()
        self.evalTop1AccValueLabel.setText("/")
        self.evalTop1AccBox = QHBoxLayout()
        self.evalTop1AccBox.addWidget(self.evalTop1AccLabel)
        self.evalTop1AccBox.addStretch(1)
        self.evalTop1AccBox.addWidget(self.evalTop1AccValueLabel)

        self.evalTop5AccLabel = QLabel()
        self.evalTop5AccLabel.setText("Best Top-5 Acc")
        self.evalTop5AccValueLabel = QLabel()
        self.evalTop5AccValueLabel.setText("/")
        self.evalTop5AccBox = QHBoxLayout()
        self.evalTop5AccBox.addWidget(self.evalTop5AccLabel)
        self.evalTop5AccBox.addStretch(1)
        self.evalTop5AccBox.addWidget(self.evalTop5AccValueLabel)

        self.evalPerformanceBox.addLayout(self.evalLossBox)
        self.evalPerformanceBox.addLayout(self.evalTop1AccBox)
        self.evalPerformanceBox.addLayout(self.evalTop5AccBox)

        #测试集最近一次结果
        self.evalLastLossLabel = QLabel()
        self.evalLastLossLabel.setText("Loss")
        self.evalLastLossValueLabel = QLabel()
        self.evalLastLossValueLabel.setText("/")
        self.evalLastLossBox = QHBoxLayout()
        self.evalLastLossBox.addWidget(self.evalLastLossLabel)
        self.evalLastLossBox.addStretch(1)
        self.evalLastLossBox.addWidget(self.evalLastLossValueLabel)

        self.evalLastTop1AccLabel = QLabel()
        self.evalLastTop1AccLabel.setText("Top-1 Acc")
        self.evalLastTop1AccValueLabel = QLabel()
        self.evalLastTop1AccValueLabel.setText("/")
        self.evalLastTop1AccBox = QHBoxLayout()
        self.evalLastTop1AccBox.addWidget(self.evalLastTop1AccLabel)
        self.evalLastTop1AccBox.addStretch(1)
        self.evalLastTop1AccBox.addWidget(self.evalLastTop1AccValueLabel)

        self.evalLastTop5AccLabel = QLabel()
        self.evalLastTop5AccLabel.setText("Top-5 Acc")
        self.evalLastTop5AccValueLabel = QLabel()
        self.evalLastTop5AccValueLabel.setText("/")
        self.evalLastTop5AccBox = QHBoxLayout()
        self.evalLastTop5AccBox.addWidget(self.evalLastTop5AccLabel)
        self.evalLastTop5AccBox.addStretch(1)
        self.evalLastTop5AccBox.addWidget(self.evalLastTop5AccValueLabel)

        self.evalLastPerformanceBox.addLayout(self.evalLastLossBox)
        self.evalLastPerformanceBox.addLayout(self.evalLastTop1AccBox)
        self.evalLastPerformanceBox.addLayout(self.evalLastTop5AccBox)

        generalMessageBox.addLayout(self.captionBox)
        generalMessageBox.addLayout(self.trainProgressBox)
        generalMessageBox.addLayout(self.trainPerformanceBox)
        generalMessageBox.addWidget(self.evalPerformanceCaptionLabel)
        generalMessageBox.addWidget(self.evalPerformaceTabs)

        #操作界面
        self.operationTab = QWidget()
        self.operationBox = QVBoxLayout(self.operationTab)
        self.controlBox = QHBoxLayout()

        self.runButton = QPushButton()
        self.runButton.setText("运行")

        self.stopButton = QPushButton()
        self.stopButton.setText("停止")

        self.controlBox.addWidget(self.runButton)
        self.controlBox.addStretch(1)
        self.controlBox.addWidget(self.stopButton)

        self.choosePathButton = QPushButton()
        self.choosePathButton.setText("选择存储路径")

        self.saveAsButton = QPushButton()
        self.saveAsButton.setText("另存为...")

        self.operationBox.addLayout(self.controlBox)
        self.operationBox.addWidget(self.choosePathButton)
        self.operationBox.addWidget(self.saveAsButton)

        #设置界面
        self.settingsTab = QWidget()
        self.settingsBox = QVBoxLayout(self.settingsTab)

        self.lrLabel = QLabel()
        self.lrLabel.setText("学习率")

        self.settingsBox.addWidget(self.lrLabel)

        #加入标签页
        tabs.addTab(self.operationTab, "操作")
        tabs.addTab(self.settingsTab, "设置")

        self.setLayout(guiBox)

        self.setWindowTitle('来啊训练啊')
        self.timer.start(100, self)
        self.show()

    def timerEvent(self, e):
        self.epochLabel.setText("Epoch " + str(int(self.arr[0])))

        self.trainProgressLabel.setText(
            str(int(self.arr[1])) + " / " + str(int(self.arr[2])))

        if self.arr[2] > 0:
            percent = int(self.arr[1] * 100 / self.arr[2])
        else:
            percent = 0
        self.trainProgressBar.setValue(percent)

        self.trainLossLabel.setText("Loss    %.2f" % self.arr[3])
        self.trainTop1AccLabel.setText("Acc@1 %.3f" % self.arr[4] + "%")
        self.trainTop5AccLabel.setText("Acc@5 %.3f" % self.arr[5] + "%")

        self.evalLossValueLabel.setText("%.2f" % self.arr[6])
        self.evalTop1AccValueLabel.setText("%.3f" % self.arr[7])
        self.evalTop5AccValueLabel.setText("%.3f" % self.arr[8])

        self.evalLastLossValueLabel.setText("%.2f" % self.arr[9])
        self.evalLastTop1AccValueLabel.setText("%.3f" % self.arr[10])
        self.evalLastTop5AccValueLabel.setText("%.3f" % self.arr[11])

        self.timer.start(100, self)
예제 #15
0
class Board(QFrame):

    msg2Statusbar = pyqtSignal(str)

    BoardWidth = 10
    BoardHeight = 22
    Speed = 300

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

        self.initBoard()


    def initBoard(self):

        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):
        return self.board[(y * Board.BoardWidth) + x]


    def setShapeAt(self, x, y, shape):
        self.board[(y * Board.BoardWidth) + x] = shape


    def squareWidth(self):
        return self.contentsRect().width() // Board.BoardWidth


    def squareHeight(self):
        return self.contentsRect().height() // Board.BoardHeight


    def start(self):

        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):

        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):

        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):

        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):

        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):

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


    def dropDown(self):

        newY = self.curY

        while newY > 0:

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

            newY -= 1

        self.pieceDropped()


    def oneLineDown(self):

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


    def pieceDropped(self):

        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):

        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):

        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):

        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):

        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)
예제 #16
0
class ScrollArea(QAbstractScrollArea):
    """A scroll area that supports kinetic scrolling and other features.

    Instance attributes:

        kineticscrolling (True): whether the wheel and pgup/pgdn keys etc use
                                 kinetic scrolling

        scrollupdatespersec (50): how many scroll updates to draw per second
                                 (50 is recommended).

    """

    kineticscrolling = True
    scrollupdatespersec = 50

    def __init__(self, parent=None, **kwds):
        super().__init__(parent, **kwds)
        self._scroller = None
        self._scrollTimer = QBasicTimer()

    def wheelEvent(self, ev):
        if self.kineticscrolling:
            self.kineticAddDelta(-ev.angleDelta())
        else:
            super().wheelEvent(ev)

    def keyPressEvent(self, ev):
        """Kinetic cursor movements."""
        hbar = self.horizontalScrollBar()
        vbar = self.verticalScrollBar()
        # add Home and End, even in non-kinetic mode
        scroll = self.kineticScrollBy if self.kineticscrolling else self.scrollBy
        if ev.key() == Qt.Key_Home:
            scroll(QPoint(0, -vbar.value()))
        elif ev.key() == Qt.Key_End:
            scroll(QPoint(0, vbar.maximum() - vbar.value()))
        elif self.kineticscrolling:
            # make arrow keys and PgUp and PgDn kinetic
            if ev.key() == Qt.Key_PageDown:
                self.kineticAddDelta(QPoint(0, vbar.pageStep()))
            elif ev.key() == Qt.Key_PageUp:
                self.kineticAddDelta(QPoint(0, -vbar.pageStep()))
            elif ev.key() == Qt.Key_Down:
                self.kineticAddDelta(QPoint(0, vbar.singleStep()))
            elif ev.key() == Qt.Key_Up:
                self.kineticAddDelta(QPoint(0, -vbar.singleStep()))
            elif ev.key() == Qt.Key_Left:
                self.kineticAddDelta(QPoint(-hbar.singleStep(), 0))
            elif ev.key() == Qt.Key_Right:
                self.kineticAddDelta(QPoint(hbar.singleStep(), 0))
            else:
                super().keyPressEvent(ev)
        else:
            super().keyPressEvent(ev)

    def scrollOffset(self):
        """Return the current scroll offset."""
        x = self.horizontalScrollBar().value()
        y = self.verticalScrollBar().value()
        return QPoint(x, y)

    def canScrollBy(self, diff):
        """Does not scroll, but return the actual distance the View would scroll.

        diff is a QPoint instance.

        """
        hbar = self.horizontalScrollBar()
        vbar = self.verticalScrollBar()

        x = min(max(0, hbar.value() + diff.x()), hbar.maximum())
        y = min(max(0, vbar.value() + diff.y()), vbar.maximum())
        return QPoint(x - hbar.value(), y - vbar.value())

    def scrollForDragging(self, pos):
        """Slowly scroll the View if pos is close to the edge of the viewport.

        Can be used while dragging things.

        """
        viewport = self.viewport().rect()
        dx = pos.x() - viewport.left() - 12
        if dx >= 0:
            dx = max(0, pos.x() - viewport.right() + 12)
        dy = pos.y() - viewport.top() - 12
        if dy >= 0:
            dy = max(0, pos.y() - viewport.bottom() + 12)
        self.steadyScroll(QPoint(dx*10, dy*10))

    def scrollTo(self, pos):
        """Scroll the View to get pos (QPoint) in the top left corner (if possible).

        Returns the actual distance moved.

        """
        return self.scrollBy(pos - self.scrollOffset())

    def scrollBy(self, diff):
        """Scroll the View diff pixels (QPoint) in x and y direction.

        Returns the actual distance moved.

        """
        hbar = self.horizontalScrollBar()
        vbar = self.verticalScrollBar()
        x = hbar.value()
        hbar.setValue(hbar.value() + diff.x())
        x = hbar.value() - x
        y = vbar.value()
        vbar.setValue(vbar.value() + diff.y())
        y = vbar.value() - y
        return QPoint(x, y)

    def kineticScrollTo(self, pos):
        """Scroll the View to get pos (QPoint) in the top left corner (if possible).

        Returns the actual distance the scroll area will move.

        """
        return self.kineticScrollBy(pos - self.scrollOffset())

    def kineticScrollBy(self, diff):
        """Scroll the View diff pixels (QPoint) in x and y direction.

        Returns the actual distance the scroll area will move.

        """
        ret = self.canScrollBy(diff)
        if diff:
            scroller = KineticScroller()
            scroller.scrollBy(diff)
            self.startScrolling(scroller)
        return ret

    def kineticAddDelta(self, diff):
        """Add diff (QPoint) to an existing kinetic scroll.

        If no scroll is active, a new one is started (like kineticScrollBy).

        """
        if isinstance(self._scroller, KineticScroller):
            self._scroller.scrollBy(self._scroller.remainingDistance() + diff)
        else:
            self.kineticScrollBy(diff)

    def steadyScroll(self, diff):
        """Start steadily scrolling diff (QPoint) pixels per second.

        Stops automatically when the end is reached.

        """
        if diff:
            self.startScrolling(SteadyScroller(diff, self.scrollupdatespersec))
        else:
            self.stopScrolling()

    def startScrolling(self, scroller):
        """Begin a scrolling operation using the specified scroller."""
        self._scroller = scroller
        if not self._scrollTimer.isActive():
            self._scrollTimer.start(1000 / self.scrollupdatespersec, self)

    def stopScrolling(self):
        """Stop scrolling."""
        if self._scroller:
            self._scrollTimer.stop()
            self._scroller = None

    def isScrolling(self):
        """Return True if a scrolling movement is active."""
        return bool(self._scroller)

    def timerEvent(self, ev):
        """Called by the _scrollTimer."""
        diff = self._scroller.step()
        # when scrolling slowly, it might be that no redraw is needed
        if diff:
            # change the scrollbars, but check how far they really moved.
            if not self.scrollBy(diff) or self._scroller.finished():
                self.stopScrolling()
예제 #17
0
파일: main_window.py 프로젝트: klekot/YaP
class YaP(QWidget):
    rate_url = 'poligon.info'
    query = ''
    query_list = []
    res_label = ''
    file_path_label = ''
    rank = 0
    file_taken = False
    res_list = []
    file_queries = []
    fname = ''
    r_count = 0
    db_path = 'keywords.db'
    xls_path = 'rating.xls'
    yandex_limits = [
        [0,  230, 0],  [1,  276, 0],  [2,  276, 0],
        [3,  276, 0],  [4,  276, 0],  [5,  230, 0],
        [6,  161, 0],  [7,  92,  0],  [8,  46,  0],
        [9,  46,  0],  [10, 46,  0],  [11, 46,  0],
        [12, 46,  0],  [13, 46,  0],  [14, 46,  0],
        [15, 46,  2],  [16, 46,  0],  [17, 46,  0],
        [18, 46,  0],  [19, 46,  0],  [20, 92,  0],
        [21, 161, 0],  [22, 230, 0],  [23, 240, 0]
    ]
    # req_date = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    req_date = str(datetime.now().strftime('%Y-%m-%d'))
    query_url = 'https://yandex.ru/search/xml?user=webmaster-poligon\
                                  &key=03.279908682:25776a70171503eb70359c5bd5b820dc&l10n=ru\
                                  &groupby=groups-on-page%3D100&lr=2&query='

    def __init__(self):
        super().__init__()
        self.initUI()
        self.search_btn.clicked.connect(self.set_query)
        self.search_btn.clicked.connect(self.start_search)
        self.qfile_btn.clicked.connect(self.showOpenDialog)
        self.sfile_btn.clicked.connect(self.db_xls)

    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        lbl = QLabel('Выбран запрос: ')
        grid.addWidget(lbl, 0, 0)
        lbl1 = QLabel('Поиск по запросу: ')
        grid.addWidget(lbl1, 3, 0)
        self.label = QLabel(self)
        grid.addWidget(self.label, 0, 1)
        self.field = QLineEdit(self)
        grid.addWidget(self.field, 3, 1)
        self.field.textChanged[str].connect(self.push_query)
        self.search_btn = QPushButton('Поиск')
        grid.addWidget(self.search_btn, 3, 2)
        self.qfile_btn = QPushButton('Файл запросов')
        grid.addWidget(self.qfile_btn, 5, 0)
        self.sfile_btn = QPushButton('Сохранить')
        grid.addWidget(self.sfile_btn, 5, 2)
        label_fake = QLabel()
        grid.addWidget(label_fake, 4, 0)
        label_fake1 = QLabel()
        grid.addWidget(label_fake1, 2, 0)
        self.label_done = QLabel()
        grid.addWidget(self.label_done, 6, 1)
        self.label_r = QLabel(self.res_label)
        grid.addWidget(self.label_r, 4, 1)
        self.label_fp = QLabel(self.file_path_label)
        grid.addWidget(self.label_fp, 5, 1)
        self.setGeometry(700, 350, 600, 200)
        self.setWindowTitle('\"YaP\" - is a Yandex ratings for Poligon.info')

        self.pbar = QProgressBar(self)
        grid.addWidget(self.pbar, 7, 1)
        self.timer = QBasicTimer()
        self.step = 0

        self.show()

    def timerEvent(self, e):
        if self.step >= 100:
            self.timer.stop()
            return
        self.step = self.step + 1
        self.pbar.setValue(self.step)

    def sql_con(self, res_list):
        conn = sqlite3.connect(self.db_path)
        db = conn.cursor()
        db.execute("select name from sqlite_master \
            where type='table' and name='requests'")
        if db.fetchone():
            for res in self.res_list:
                if len(self.file_queries) == 0:
                    k = (self.query.encode('utf-8').decode('cp1251'),
                         self.req_date,)
                    db.execute("select * from requests \
                            where keyword=? and date=?", k)
                    if db.fetchone():
                        db.execute("delete from requests \
                            where keyword=? and date=?", k)
                    else:
                        continue
                else:
                    for q in self.file_queries:
                        k = (q, self.req_date,)
                        db.execute("select * from requests \
                                where keyword=? and date=?", k)
                        if db.fetchone():
                            db.execute("delete from requests \
                                where keyword=? and date=?", k)
                        else:
                            continue
            db.executemany(
                "insert into requests values (?, ?, ?)",
                self.res_list)
        else:
            db.execute("create table requests (keyword, position, date)")
            db.executemany(
                "insert into requests values (?, ?, ?)",
                self.res_list)
        conn.commit()
        db.close()
        conn.close()

    def db_xls(self):
        conn = sqlite3.connect(self.db_path)
        db = conn.cursor()
        db.execute("select name from sqlite_master \
            where type='table' and name='requests'")
        wb = Workbook()
        ws = wb.add_sheet('keywords')
        plain = easyxf('')
        if db.fetchone():
            for r, row in enumerate(db.execute("select * from requests")):
                for c, col in enumerate(row):
                    if (type(col) is int) != True:
                        ws.write(r, c, col.encode('cp1251')
                                 .decode('utf-8'), plain)
                    else:
                        ws.write(r, c, col, plain)
                    print(col)
                wb.save(self.xls_path)
        db.close()
        conn.close()

    def showOpenDialog(self):
        self.fname, _ = QFileDialog.getOpenFileName(self, 'Open file',
                                                    'C:\\Users\\gnato\\\
                                                    Desktop\\Igor\\progs\\\
                                                    python_progs\\YaP\\')
        if len(self.fname) > 0:
            book = xlrd.open_workbook(self.fname, 'rt', formatting_info=True)
            sh = book.sheet_by_index(0)
        else:
            pass
        for i in range(sh.nrows):
            self.query_list.append(sh.cell_value(i, 0))
        print('query_list is: ')
        for l in self.query_list:
            print(l.encode('utf-8').decode('cp1251'))
        self.file_taken = True
        fname_chars = []
        for char in self.fname:
            if (char == '/'):
                fname_chars.append('\\')
            else:
                fname_chars.append(char)
        win_path = ''.join(fname_chars)
        self.label_fp.setText(win_path)
        self.label_fp.adjustSize()
        self.start_search(self.event)

    def keyPressEvent(self, event):
        if type(event) == QKeyEvent:
            if event.key() == Qt.Key_Escape:
                self.close()
            elif event.key() == Qt.Key_Return:
                self.set_query(self)
                self.start_search(self)

    def set_query(self, event):
        self.query = self.field.text()
        self.rank = 0
        self.file_queries = []

    def push_query(self, query):
        self.label.setText(query)
        self.label.adjustSize()

    def start_search(self, event):
        if self.timer.isActive():
            self.timer.stop()
        else:
            self.timer.start(100, self)
            self.label_done.setText(
                'Запросы обработаны, результаты занесены в базу данных.\n\
Для сохранения в файл нажмите кнопку \"Сохранить\".')
        if self.file_taken:
            for j, item in enumerate(self.query_list):
                self.query = self.query_list[j]
                r = requests.get(self.query_url + self.query)
                self.r_count += 1
                # функция limit() может быть вызвана только один раз          #
                # во избежание неправильных показателей счётчика.             #
                limit_data = limit(self.r_count, self.db_path, self.req_date) #
                # ########################################################### #
                if (limit_data[0]):
                    result = r.text
                    result_list = result.split('<url>')
                    for i, item in enumerate(result_list):
                        if self.rate_url in item:
                            self.rank += i
                            break
                    self.res_list.append((
                        self.query.encode('utf-8').decode('cp1251'),
                        self.rank,
                        self.req_date,))
                    self.file_queries.append(
                        self.query.encode('utf-8').decode('cp1251'))
                    limit_resume = str(limit_data[1]) + ' - Winter is close!'
                else:
                    limit_resume = str(limit_data[1]) +\
                        'Hour limit is here... Wait about ' +\
                        str(60 - int(datetime.now().strftime('%M'))) +\
                        ' minuntes, please!'
            self.sql_con(self.res_list)
            print(limit_resume)
            print(int(datetime.now().strftime('%Y-%m-%d')))
            print(int(datetime.now().strftime('%Y-%m-%d'))-1)
        else:
            r = requests.get(self.query_url + self.query)
            self.r_count += 1
            result = r.text
            result_list = result.split('<url>')
            for i, item in enumerate(result_list):
                if self.rate_url in item:
                    self.rank += i
                    break
            if self.rank != 0:
                self.res_label = ('По запросу \"' + self.query + '\" сайт poligon.info \
находится на ' + str(self.rank) + '-й позиции.\nДата запроса : '
                    + self.req_date + '.')
                self.label_r.setText(self.res_label)
                self.label_r.adjustSize()
                self.res_list.append((
                    self.query.encode('utf-8').decode('cp1251'),
                    self.rank,
                    self.req_date,))
                self.sql_con(self.res_list)
            else:
                self.res_label = ('По запросу \"' + self.query + '\" сайт poligon.info \
находится ниже 100-й позиции.\nДата запроса : '
                                  + self.req_date + '.')
                self.label_r.setText(self.res_label)
                self.label_r.adjustSize()
                self.res_list.append((
                    self.query.encode('utf-8').decode('cp1251'),
                    self.rank,
                    self.req_date,))
                self.sql_con(self.res_list)
                print('end')
                print(self.res_list)
예제 #18
0
class IP_Phone_Tester(QtWidgets.QMainWindow, Ui_IP_Phone_Tester):

    # определяем константы
    MODE_TEST = False  # вкл. тестовый режим
    CUR_CMD = {  # возможные состояния программы
        "NONE": 0,
        "IDLE": 1,
    }
    BAUDRATES = ['1200', '9600', '19200', '38400', '57600',
                 '115200']  # возможные значения скоростей для RS-232
    LENGTH_LED_CMD = 8  # длина принимаемого пакета
    READ_BYTES = 100  # количество байт для чтения
    MAX_WAIT_BYTES = 200  # максимальное количество байт в буфере порта на прием
    NUMBER_SCAN_PORTS = 20  # количество портов для сканирования
    START = 0x40
    STOP = 0x5E
    SEPARATOR = 0x7C
    CMD_TX = {
        'IDLE': bytearray([0x40, 0x30, 0x7C, 0x7C, 0x5E]),
        'REQ_DIALTONE': bytearray([0x40, 0x34, 0x7C, 0x7C, 0x5E]),
        'LED1_ON': bytearray([0x40, 0x35, 0x7C, 0x31, 0x7C, 0x31, 0x5E]),
        'LED2_ON': bytearray([0x40, 0x35, 0x7C, 0x31, 0x7C, 0x32, 0x5E]),
        'LED1_BLINK': bytearray([0x40, 0x35, 0x7C, 0x32, 0x7C, 0x31, 0x5E]),
        'LED2_BLINK': bytearray([0x40, 0x35, 0x7C, 0x32, 0x7C, 0x32, 0x5E]),
        'LED1_OFF': bytearray([0x40, 0x35, 0x7C, 0x30, 0x7C, 0x31, 0x5E]),
        'LED2_OFF': bytearray([0x40, 0x35, 0x7C, 0x30, 0x7C, 0x32, 0x5E]),
        'LEDS_ON': bytearray([0x40, 0x36, 0x7C, 0x31,
                              0x7C]),  # последние 3 байта не показаны
        'LEDS_OFF': bytearray([0x40, 0x36, 0x7C, 0x30,
                               0x7C]),  # последние 3 байта не показаны
        'LEDS_BLINK': bytearray([0x40, 0x36, 0x7C, 0x32,
                                 0x7C]),  # последние 3 байта не показаны
        'HENDSET_ON': bytearray([0x40, 0x37, 0x7C, 0x31, 0x7C, 0x5E]),
        'HENDSET_OFF': bytearray([0x40, 0x37, 0x7C, 0x30, 0x7C, 0x5E]),
        'MIC_ON': bytearray([0x40, 0x38, 0x7C, 0x31, 0x7C, 0x5E]),
        'MIC_OFF': bytearray([0x40, 0x38, 0x7C, 0x30, 0x7C, 0x5E]),
        'SPEAK_ON': bytearray([0x40, 0x39, 0x7C, 0x31, 0x7C, 0x5E]),
        'SPEAK_OFF': bytearray([0x40, 0x39, 0x7C, 0x30, 0x7C, 0x5E]),
        'HORN_ON': bytearray([0x40, 0x31, 0x30, 0x7C, 0x31, 0x7C, 0x5E]),
        'HORN_OFF': bytearray([0x40, 0x31, 0x30, 0x7C, 0x30, 0x7C, 0x5E]),
        'SET_VOLUME': bytearray([0x40, 0x31, 0x32, 0x7C]),
    }

    # инициализация окна
    # pyuic5 UI_IP_Phone_Tester.ui -o UI_IP_Phone_Tester.py
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        # инициализация интерфейса
        self.setupUi(self)
        # определяем таймер
        self.timer_RX_RS = QBasicTimer()
        self.timer_RX_RS.stop()
        # подключаем модули
        self.rs = RS_IP_Phone_Tester()  # подключение функций работы по RS
        # инициализация переменных
        self.Init_Var()
        # настройка действий по кнопкам
        self.Init_Widgets()

    def test(self):
        for i in 'hallo world':
            if i == 'a':
                break
            else:
                print('есть')
        else:
            print('Буквы a в строке нет')

    @property
    def status_new(self):
        '''
        # установка нового значения свойства status_new
        '''
        return self.__Status_new

    @status_new.setter
    def status_new(self, status):
        '''
        # установка нового значения свойства status_new
        '''
        self.__Status_new = status

    def Init_Var(self):
        self.__Status_new = self.CUR_CMD["NONE"]  #текущее состояние
        self.cb_State = []
        self.rs_receive_pack = bytearray()
        self.last_LED = '30'
        for i in range(1, 31):
            self.cb_State.append(False)

    def Init_Widgets(self):
        #настройка списка для выбора порта
        self.comboBox_COM.addItems(self.rs.scan_COM_ports())
        self.comboBox_COM.setCurrentIndex(0)
        #добавляем нужные скорости в comboBox_Baudrate
        self.comboBox_Baudrate.addItems(self.BAUDRATES)
        self.comboBox_Baudrate.setCurrentIndex(
            4)  #добавляем нужные скорости в comboBox_Baudrate
        # обработчики для кнопок
        self.pushButton_open_COM.clicked.connect(self.pb_Open_COM_Header)
        self.pushButton_close_COM.clicked.connect(self.pb_Close_COM_Header)
        self.pushButton_Check_Connect.clicked.connect(
            self.pb_Check_Connect_Header)
        self.pushButton_LED_1.clicked.connect(self.pb_LED1_Header)
        self.pushButton_LED_2.clicked.connect(self.pb_LED2_Header)
        self.pushButton_Hendset.clicked.connect(self.pb_Hendset_Header)
        self.pushButton_Mic.clicked.connect(self.pb_Mic_Header)
        self.pushButton_Speak.clicked.connect(self.pb_Speak_Header)
        self.pushButton_Horn.clicked.connect(self.pb_Horn_Header)
        self.pushButton_Next_LED.clicked.connect(self.pb_Next_LED_Header)
        self.pushButton_Next_LED_OFF.clicked.connect(
            self.pb_Next_LED_OFF_Header)
        self.pushButton_Volume.clicked.connect(self.pb_Volume_Header)
        self.verticalSlider_Volume.valueChanged.connect(self.sl_Volume_Header)
        for i in range(1, 31):
            eval('self.checkBox_%i.stateChanged.connect(self.cb_Header)' % i)

    def pb_Open_COM_Header(self):
        '''
        :return:
        '''
        self.status_new = self.CUR_CMD["IDLE"]
        self.comboBox_COM.setDisabled(1)
        self.comboBox_Baudrate.setDisabled(1)
        baudrate = int(self.comboBox_Baudrate.currentText())
        nom_com_port = self.comboBox_COM.currentText()
        # конфигурируем RS
        self.rs.Serial_Config(baudrate, nom_com_port)
        self.rs.Init_RS_Var(baudrate)
        # изменяем видимость кнопок
        self.Enable_Widgets()
        self.timer_RX_RS.start(
            self.rs.time_to_rx,
            self)  #отправляем запрос защитного кода через self.time_to_rx мс

    def pb_Close_COM_Header(self):
        '''
        #*********************************************************************
        # активация кнопок после выбора порта и скорости
        #*********************************************************************
        :return:
        '''
        self.rs.Recieve_RS_Data()
        # закрываем порт
        if self.rs.Check_Serial:
            self.rs.Serial_Close()
        # изменяем видимость кнопок
        self.Disable_Widgets()
        self.status_new = self.CUR_CMD['NONE']

    def pb_Check_Connect_Header(self):
        self.rs.Send_Command(self.CMD_TX['REQ_DIALTONE'], self.MODE_TEST)

    def pb_LED1_Header(self, d):
        if self.pushButton_LED_1.isChecked():
            # кнопка нажата
            if self.radioButton_Perm.isChecked():
                self.rs.Send_Command(self.CMD_TX['LED1_ON'], self.MODE_TEST)
            else:
                self.rs.Send_Command(self.CMD_TX['LED1_BLINK'], self.MODE_TEST)
        else:
            # кнопка отжата
            self.rs.Send_Command(self.CMD_TX['LED1_OFF'], self.MODE_TEST)

    def pb_LED2_Header(self):
        if self.pushButton_LED_2.isChecked():
            # кнопка нажата
            if self.radioButton_Perm.isChecked():
                self.rs.Send_Command(self.CMD_TX['LED2_ON'], self.MODE_TEST)
            else:
                self.rs.Send_Command(self.CMD_TX['LED2_BLINK'], self.MODE_TEST)
        else:
            # кнопка отжата
            self.rs.Send_Command(self.CMD_TX['LED2_OFF'], self.MODE_TEST)

    def pb_Hendset_Header(self):
        if self.pushButton_Hendset.isChecked():
            # кнопка нажата
            self.rs.Send_Command(self.CMD_TX['HENDSET_ON'], self.MODE_TEST)
        else:
            # кнопка отжата
            self.rs.Send_Command(self.CMD_TX['HENDSET_OFF'], self.MODE_TEST)

    def pb_Mic_Header(self):
        if self.pushButton_Mic.isChecked():
            # кнопка нажата
            self.rs.Send_Command(self.CMD_TX['MIC_ON'], self.MODE_TEST)
        else:
            # кнопка отжата
            self.rs.Send_Command(self.CMD_TX['MIC_OFF'], self.MODE_TEST)

    def pb_Speak_Header(self):
        if self.pushButton_Speak.isChecked():
            # кнопка нажата
            self.rs.Send_Command(self.CMD_TX['SPEAK_ON'], self.MODE_TEST)
        else:
            # кнопка отжата
            self.rs.Send_Command(self.CMD_TX['SPEAK_OFF'], self.MODE_TEST)

    def pb_Horn_Header(self):
        if self.pushButton_Horn.isChecked():
            # кнопка нажата
            self.rs.Send_Command(self.CMD_TX['HORN_ON'], self.MODE_TEST)
        else:
            # кнопка отжата
            self.rs.Send_Command(self.CMD_TX['HORN_OFF'], self.MODE_TEST)

    def cb_Header(self):
        for i in range(1, 31):
            state = eval('self.checkBox_%i.isChecked()' % i)
            data = bytearray()
            if state == True and self.cb_State[i - 1] == False:
                self.cb_State[i - 1] = True
                if self.radioButton_Perm.isChecked():
                    data += self.CMD_TX['LEDS_ON']
                else:
                    data += self.CMD_TX['LEDS_BLINK']
                self.last_LED = str(i - 1)
                if i < 11:
                    self.last_LED = '0' + self.last_LED
                # добавляем номер светодиода
                data += ord(self.last_LED[0]).to_bytes(1, 'little')
                data += ord(self.last_LED[1]).to_bytes(1, 'little')
                data += self.STOP.to_bytes(1, 'little')
                # отправляем команду
                self.rs.Send_Command(data, self.MODE_TEST)
            elif state == False and self.cb_State[i - 1] == True:
                self.cb_State[i - 1] = False
                data += self.CMD_TX['LEDS_OFF']
                self.last_LED = str(i - 1)
                if i < 11:
                    self.last_LED = '0' + self.last_LED
                # добавляем номер светодиода
                data += ord(self.last_LED[0]).to_bytes(1, 'little')
                data += ord(self.last_LED[1]).to_bytes(1, 'little')
                data += self.STOP.to_bytes(1, 'little')
                # отправляем команду
                self.rs.Send_Command(data, self.MODE_TEST)
        return True

    def pb_Volume_Header(self):
        # отправляем команду SET_VOLUME
        data = bytearray()
        data += self.CMD_TX['SET_VOLUME']
        volume = self.label_main_Volume.text()
        if len(volume) == 1:
            data += ord('0').to_bytes(1, 'little')
            data += ord(volume).to_bytes(1, 'little')
            data += self.STOP.to_bytes(1, 'little')
        else:
            data += ord(volume[0]).to_bytes(1, 'little')
            data += ord(volume[1]).to_bytes(1, 'little')
            data += self.STOP.to_bytes(1, 'little')
        self.rs.Send_Command(data, self.MODE_TEST)

    def sl_Volume_Header(self):
        self.label_main_Volume.setText(str(self.verticalSlider_Volume.value()))

    def pb_Next_LED_Header(self):
        data = bytearray()
        if self.radioButton_Perm.isChecked():
            data += self.CMD_TX['LEDS_ON']
        else:
            data += self.CMD_TX['LEDS_BLINK']
        num = int(self.last_LED) + 1
        self.last_LED = str(num)
        if num < 10:
            self.last_LED = '0' + self.last_LED
        elif num >= 30:
            self.last_LED = '00'
            num = 0
        eval('self.checkBox_%i.setCheckState(2)' % (num + 1))
        # добавляем номер светодиода
        data += ord(self.last_LED[0]).to_bytes(1, 'little')
        data += ord(self.last_LED[1]).to_bytes(1, 'little')
        data += self.STOP.to_bytes(1, 'little')
        # отправляем команду
        self.rs.Send_Command(data, self.MODE_TEST)

    def pb_Next_LED_OFF_Header(self):
        data = bytearray()
        data += self.CMD_TX['LEDS_OFF']
        num = int(self.last_LED) + 1
        self.last_LED = str(num)
        if num < 10:
            self.last_LED = '0' + self.last_LED
        elif num >= 30:
            self.last_LED = '00'
            num = 0
        eval('self.checkBox_%i.setCheckState(0)' % (num + 1))
        # добавляем номер светодиода
        data += ord(self.last_LED[0]).to_bytes(1, 'little')
        data += ord(self.last_LED[1]).to_bytes(1, 'little')
        data += self.STOP.to_bytes(1, 'little')
        # отправляем команду
        self.rs.Send_Command(data, self.MODE_TEST)

    def Enable_Widgets(self):
        self.comboBox_COM.setDisabled(1)
        self.comboBox_Baudrate.setDisabled(1)
        self.pushButton_open_COM.setDisabled(1)
        self.pushButton_close_COM.setEnabled(1)
        self.radioButton_Perm.setEnabled(1)
        self.radioButton_Perm.setChecked(1)
        self.radioButton_Blink.setEnabled(1)
        self.pushButton_Next_LED.setEnabled(1)
        self.pushButton_LED_1.setEnabled(1)
        self.pushButton_LED_2.setEnabled(1)
        self.pushButton_Hendset.setEnabled(1)
        self.pushButton_Mic.setEnabled(1)
        self.pushButton_Speak.setEnabled(1)
        self.pushButton_Horn.setEnabled(1)
        self.pushButton_Check_Connect.setEnabled(1)
        self.pushButton_Volume.setEnabled(1)
        self.pushButton_Next_LED_OFF.setEnabled(1)
        self.verticalSlider_Volume.setEnabled(1)
        for i in range(1, 31):
            eval('self.checkBox_%i.setEnabled(1)' % i)

    def Disable_Widgets(self):
        self.comboBox_COM.setEnabled(1)
        self.comboBox_Baudrate.setEnabled(1)
        self.pushButton_open_COM.setEnabled(1)
        self.pushButton_close_COM.setDisabled(1)
        self.radioButton_Perm.setDisabled(1)
        self.radioButton_Blink.setDisabled(1)
        self.pushButton_Next_LED.setDisabled(1)
        self.pushButton_LED_1.setDisabled(1)
        self.pushButton_LED_2.setDisabled(1)
        self.pushButton_Hendset.setDisabled(1)
        self.pushButton_Mic.setDisabled(1)
        self.pushButton_Speak.setDisabled(1)
        self.pushButton_Horn.setDisabled(1)
        self.pushButton_Check_Connect.setDisabled(1)
        self.pushButton_Volume.setDisabled(1)
        self.pushButton_Next_LED_OFF.setDisabled(1)
        self.verticalSlider_Volume.setDisabled(1)
        for i in range(1, 31):
            eval('self.checkBox_%i.setDisabled(1)' % i)
            eval('self.checkBox_%i.setChecked(0)' % i)

    def Extract_Command(self, data_in):
        """
        парсинг полученного пакета
        """
        num = 0
        start_ok = False
        data = bytearray()
        # обрезаем начало до стартового символа
        for d in data_in:
            if d == self.START:
                break
            else:
                num += 1
        if num == len(data_in):
            # в принятых данных нет стартового байта, возвращаем исходный пакет
            return (data, data_in)
        else:
            tail = num
            # выделяем команду и остаток
            for d in data_in[num:]:
                tail += 1
                if d == self.START and start_ok == False:
                    data += d.to_bytes(1, 'little')
                    start_ok = True
                elif d == self.STOP and start_ok == True:
                    data += d.to_bytes(1, 'little')
                    start_ok = False
                    return (data, data_in[tail:])
                elif start_ok == True:
                    data += d.to_bytes(1, 'little')

    def Parsing_RX_Data(self, data):
        '''
        Парсинг принятых данных в data и изменение внешнего вида окна
        :param data:
        :return: True/ False
        '''
        if len(data) > 1:
            if data[0] == self.START and data[-1:] == bytearray([self.STOP]):
                if data[1] == 0x33 and data[2] == 0x7C and data[4] == 0x7C:
                    try:
                        num = int(chr(data[5]) + chr(data[6])) + 1
                    except ValueError:
                        return False
                    if data[3] == 0x30:  # кнопка отжата
                        text = 'отжата'
                        text_for_command = 'self.frame_%i.setStyleSheet("background-color: rgb(255, 117, 53);")'
                        eval('self.label_t%i.setText("%s")' % (num, text))
                        eval(text_for_command % num)
                        return True
                    elif data[3] == 0x31:  # кнопка нажата
                        text = 'нажата'
                        text_for_command = 'self.frame_%i.setStyleSheet("background-color: rgb(0, 150, 53);")'
                        eval('self.label_t%i.setText("%s")' % (num, text))
                        eval(text_for_command % num)
                        return True
                elif data[1] == 0x31 and data[2] == 0x7C and data[4] == 0x7C:
                    self.frame_Connect.setStyleSheet(
                        "background-color: rgb(0, 150, 53);")
                    return True
        return False

    def analyze_pack(self):
        '''
        #*********************************************************************
        # анализ принятых данных из RS
        #*********************************************************************
        :return:
        '''
        # проверка на стартовую и стоповую посылку

        # показать принятые данные в тестовом режиме
        if self.MODE_TEST:
            self.rs.Show_RX_DATA()
            self.rs_receive_pack = bytearray(
                [0x40, 0x31, 0x7C, 0x30, 0x7C, 0x5E])
        # производим разбор принятого пакета
        data, self.rs_receive_pack = self.Extract_Command(self.rs_receive_pack)
        res = self.Parsing_RX_Data(data)
        # проверка была ли ошибка длины в принятых данных
        if res:
            return True
        else:
            return False

    def timerEvent(self, e):
        '''
        #*********************************************************************
        # обработка событий по таймеру
        #*********************************************************************
        :param e:
        :return:
        '''
        self.timer_RX_RS.stop()  #выключаем таймер
        if self.status_new != self.CUR_CMD['NONE']:
            self.rs_receive_pack += self.rs.Recieve_RS_Data()  #получаем аднные
            #есть ли принятые данные
            if self.rs_receive_pack != bytearray() or self.MODE_TEST:
                # анализируем полученные данные
                if not self.analyze_pack():
                    QtWidgets.QMessageBox.warning(self, 'Ошибка',
                                                  "Ошибка приема",
                                                  QtWidgets.QMessageBox.Ok)
            self.timer_RX_RS.start(self.rs.time_to_rx, self)
        return
예제 #19
0
class GraphicsView(QGraphicsView):
    """Viewport-ul aplicatiei

    Aceasta clasa este responsabila pentru vizualizarea
    nodurilor, muchiilor, respectiv si a animatiilor
    acestora.

    Atribute
    --------
    frame_graph : QFrame
        este parintele viewport-ului
    engine : GraphEngine
        engin-ul grafului
    frameRateTimer : QBasicTimer
        timer-ul pentru a urmarii frame rate-ul
    scene : QGraphicsScene
        scene-ul unde se vor afisa nodurile si muchiile

    Metode
    ------
    resizeEvent(event)
        redimensionarea viewport-ului
    timerEvent(timerEvent)
        urmareste frame rate-ul
    """
    def __init__(self, parent):
        super(GraphicsView, self).__init__(parent=parent)
        self.setRenderHint(QPainter.HighQualityAntialiasing)

        self.frame_graph = parent
        self.engine = GraphEngine(self)

        # Setarea la 60 de frame-uri (refresh o data la 17 milisec)
        self.frameRateTimer = QBasicTimer()
        self.frameRateTimer.start(17, self)

        # Setarea scene-ului
        self.scene = QGraphicsScene(self)
        self.setScene(self.scene)
        self.show()

    def resizeEvent(self, event):
        """Redimensionarea viewport-ului

        La fiecare redimensionare a viewport-ului trebuie redimensionat
        si scene-ul pntru a asigura redarea corecta a elementelor grafului
        """

        self.scene.setSceneRect(QRectF(0, 0, self.width(), self.height()))

    def timerEvent(self, timerEvent):
        """Urmareste frame rate-ul aplicatiei

        La fiecare 17 milisecunde se va aplea aceasta funtie, se vor
        face modificarile corespunzatoare (actualizarea pozitilor nodurilor
        si a randarea muchiilor) apoi se va apela funtia update() pentru a
        anunta viewport-ul ca s-au facut modificari
        """

        if self.engine.force_mode:
            self.engine.update_nodes()
            self.engine.update_connections()
        self.engine.draw_edges()
        self.update()
예제 #20
0
class Board(QFrame):
    # 俄罗斯方块的一切逻辑操作在这里(旋转控制/满层消除/gameover判断/定时器判断/图形渲染)
    msg2status_bar = pyqtSignal(str)

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

        self.is_paused = False  # 是否被暂停
        self.num_lines_removed = 0  # 被删除的行数
        self.game_start = True
        self.waiting_new_shape = False

        self.cur_x = 0
        self.cur_y = 0
        self.cur_shape = None

        self.setFocusPolicy(Qt.StrongFocus)  # 界面没有按钮时,设置聚焦
        self.timer = QBasicTimer()
        self.boards = []
        self.clear_board()

    def clear_board(self):
        self.boards = [0 for i in range(WIDTH_GRID * HEIGHT_GRID)]

    def start(self):
        self.new_shape()
        self.timer.start(SPEED, self)

    def paintEvent(self, e):
        self.draw_shape()

    def new_shape(self):
        # 新建 shape
        self.cur_x = WIDTH_GRID // 2
        self.cur_y = 0
        self.cur_shape = Shape()
        self.cur_shape.set_random_shape()
        self.cur_shape.set_shape_coors(self.cur_shape.shape_type)

        if not self.move_shape(self.cur_shape, 0, 1):
            self.timer.stop()
            self.msg2status_bar.emit('Game Over!')
            self.game_start = False
            if self.cur_shape_has_repeat():
                self.cur_shape = Shape()
        self.update()

    def cur_shape_has_repeat(self):
        for i in range(len(self.cur_shape.coors)):
            x = self.cur_shape.get_x(i)
            y = self.cur_shape.get_y(i)
            if self.get_shape_in_boards(x, y) != ShapeType.No_shape:
                return True
        return False

    def timerEvent(self, e):
        if e.timerId() == self.timer.timerId():
            # time.sleep(1)
            if self.waiting_new_shape:
                self.waiting_new_shape = False
                self.set_shape_in_boards()
                self.remove_full_lines()
            else:
                self.shape_down1line(0, 1)
        else:
            return super(Board, self).timerEvent(e)

    def shape_down1line(self, x_offset, y_offset):
        # shape 往下移动一行
        res = self.move_shape(self.cur_shape, x_offset, y_offset)
        # if res is False:
        #     self.set_shape_in_boards()
        #     self.remove_full_lines()
        return res

    def shape_drop_down(self):
        # 直接移动到底部
        while self.shape_down1line(0, 1):
            pass

    def shape_pause(self):
        if self.is_paused:
            self.timer.start(SPEED, self)
            self.msg2status_bar.emit("分数:" + str(self.num_lines_removed))
        else:
            self.timer.stop()
            self.msg2status_bar.emit("暂停")

        self.is_paused = not self.is_paused
        self.update()

    def keyPressEvent(self, event):
        key = event.key()

        if not self.game_start:
            return super(Board, self).keyPressEvent(event)
        if self.is_paused and key != Qt.Key_P:
            return super(Board, self).keyPressEvent(event)

        if key == Qt.Key_Up:
            # 上:左转
            self.move_shape(self.cur_shape.rotate_left(), 0, 0)
        elif key == Qt.Key_Down:
            # 下:右转
            self.move_shape(self.cur_shape.rotate_right(), 0, 0)
        elif key == Qt.Key_Left:
            # 左移
            self.shape_down1line(-1, 0)
        elif key == Qt.Key_Right:
            # 右移
            self.shape_down1line(1, 0)
        elif key == Qt.Key_P:
            # 暂停
            self.shape_pause()
        elif key == Qt.Key_Space:
            # 空格:直接下到最后一行
            self.shape_drop_down()
        else:
            return super(Board, self).keyPressEvent(event)

    def move_shape(self, shape, x_offset, y_offset):
        for i in range(len(shape.coors)):
            x = shape.get_x(i) + self.cur_x
            y = -shape.get_y(i) + self.cur_y

            if x + x_offset < 0 or x + x_offset >= WIDTH_GRID or y > HEIGHT_GRID - 1:
                # 设定不能超出边界
                return None
            if y < 0:
                continue
            # if y == HEIGHT_GRID - 1:
            #     # 接触到了下边界
            #     self.set_shape_in_boards()
            #     self.remove_full_lines()
            #     pass
            if y == HEIGHT_GRID - 1 or self.boards[self.get_index_in_boards(
                    x, y + 1)] != ShapeType.No_shape:
                # 接触到了下边界 或 如果 x y 这个坐标在 boards 中不是空形状,返回 False
                self.waiting_new_shape = True
                return False

        self.cur_x += x_offset
        self.cur_y += y_offset
        self.cur_shape = shape
        self.update()
        return True

    def remove_full_lines(self):
        # 删除所有满行
        lines = list(
            set([
                self.cur_y - self.cur_shape.get_y(i)
                for i in range(len(self.cur_shape.coors))
            ]))
        remove_lines = []

        for line in lines:
            for i in range(line * WIDTH_GRID, line * WIDTH_GRID + WIDTH_GRID):
                if self.boards[i] == ShapeType.No_shape:
                    break
            else:
                remove_lines.append(line)

        if remove_lines:
            remove_lines.sort()
            for remove_line in remove_lines:
                while remove_line > 0:
                    for i in range(remove_line * WIDTH_GRID,
                                   remove_line * WIDTH_GRID + WIDTH_GRID):
                        self.boards[i] = self.boards[i - WIDTH_GRID]
                    remove_line -= 1

        if len(remove_lines) > 0:
            self.num_lines_removed += len(remove_lines)
            self.msg2status_bar.emit("分数:" + str(self.num_lines_removed))

        self.new_shape()

    def get_shape_in_boards(self, x, y):
        return self.boards[self.get_index_in_boards(x, y)]

    def set_shape_in_boards(self):
        for i in range(len(self.cur_shape.coors)):
            x = self.cur_shape.get_x(i) + self.cur_x
            y = -self.cur_shape.get_y(i) + self.cur_y
            if y < 0 or x < 0:
                continue
            self.set_boards_shape_type(x, y, self.cur_shape.shape_type)

    def set_boards_shape_type(self, x, y, shape_type):
        count = self.get_index_in_boards(x, y)
        self.boards[count] = shape_type

    @classmethod
    def get_index_in_boards(cls, x, y):
        return y * WIDTH_GRID + x

    def draw_shape(self):
        qp = QPainter()
        qp.begin(self)

        for i in range(len(self.cur_shape.coors)):
            if self.cur_shape.shape_type == ShapeType.No_shape:
                break
            self.painter_square(qp, self.cur_x + self.cur_shape.get_x(i),
                                self.cur_y - self.cur_shape.get_y(i), 1, 1,
                                self.cur_shape.shape_type)

        for i in range(WIDTH_GRID):
            for j in range(HEIGHT_GRID):
                shape_type = self.get_shape_in_boards(i, j)
                if shape_type != ShapeType.No_shape:
                    self.painter_square(qp, i, j, 1, 1, shape_type)

        qp.end()

    def every_square_per_width(self):
        return self.contentsRect().width() // WIDTH_GRID

    def every_square_per_height(self):
        return self.contentsRect().height() // HEIGHT_GRID

    def painter_square(self, qp, x, y, width, height, shape_type):
        # 根据长宽和起始地点画框
        x *= self.every_square_per_width()
        y *= self.every_square_per_height()
        width *= self.every_square_per_width()
        height *= self.every_square_per_height()

        color = QColor(ShapeType.Shape_Colors[shape_type])
        qp.fillRect(x + 1, y + 1, width - 1, height - 2, color)

        qp.setPen(color.lighter())
        qp.drawLine(x, y, x + width - 1, y)
        qp.drawLine(x, y, x, y + height - 1)
        qp.setPen(color.darker())
        qp.drawLine(x + width - 1, y + 1, x + width - 1, y + height - 1)
        qp.drawLine(x + 1, y + height - 1, x + width - 1, y + height - 1)
예제 #21
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        #文件分片大小
        self.kuaidx = 2097152
        #self.kuaidx = 20971520
        self.tokenurl = "http://11.2.77.3:30089/portal-test/user/login/account"
        self.upfileurl = "http://11.2.77.3:30089/portal-test/store/file/upload"
        self.useridurl = "http://11.2.77.3:30089/portal-test/user/person/get"
        self.changepemurl = "http://11.2.77.3:30089/portal-test/store/file/merge"
        self.rbinfo = "内部"
        self.initUi3()
        self.ffsize = 123
        self.totalchunk = 123
        self.username = 123
        self.userid = 123
        self.file_up = 123
        self.filename_up = 123
        self.step = 123
        self.work = dfThread(self.ffsize, self.totalchunk, self.username,
                             self.userid, self.file_up, self.filename_up,
                             self.step)

    def initUi(self):
        lcd = QLCDNumber(self)
        lab = QLabel(self)
        #dial = QDial(self)
        dial = QSlider(self)

        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('忽然之间')

        lab.setGeometry(90, 80, 70, 60)
        lcd.setGeometry(100, 50, 150, 60)
        dial.setGeometry(120, 120, 100, 100)

        dial.valueChanged.connect(lcd.display)
        lab.setText('a')
        self.show()

    def initUi2(self):
        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('CASJC')
        self.lab = QLabel('方向', self)
        self.lab.setGeometry(150, 100, 50, 50)
        self.show()

    def initUi3(self):
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('CASJC')

        self.formlayout = QFormLayout()

        self.rb1 = QRadioButton('线上', self)
        self.rb2 = QRadioButton('内部', self)
        self.rb2.setChecked(True)

        self.bg1 = QButtonGroup(self)
        self.bg1.addButton(self.rb1, 11)
        self.bg1.addButton(self.rb2, 22)

        self.info1 = ""
        self.info2 = ""

        self.bg1.buttonClicked.connect(self.rbclicked)

        self.nameLabel = QLabel("账号")
        self.nameLineEdit = QLineEdit("")

        self.introductionLabel = QLabel("密码")
        self.introductionLineEdit = QLineEdit("")
        #self.introductionLineEdit = QTextEdit("")

        self.bt1 = QPushButton('登录', self)
        self.bt1.setGeometry(115, 150, 70, 30)
        self.bt1.setToolTip('登录先进云计算平台')

        self.formlayout.addRow(self.rb1, self.rb2)
        self.formlayout.addRow(self.nameLabel, self.nameLineEdit)
        self.formlayout.addRow(self.introductionLabel,
                               self.introductionLineEdit)
        #formlayout.addRow(fileup,self.filebutton)
        self.formlayout.addRow(self.bt1)
        self.setLayout(self.formlayout)

        self.bt1.clicked.connect(self.Casjc_login)

        self.show()

    def rbclicked(self):
        sender = self.sender()
        if sender == self.bg1:
            if self.bg1.checkedId() == 11:
                self.tokenurl = "https://www.casjc.com/portal/user/login/account"
                self.upfileurl = "https://console.casjc.com/portal/store/file/upload"
                self.useridurl = "https://www.casjc.com/portal/user/person/get"
                self.changepemurl = "https://console.casjc.com/portal/store/file/merge"
                self.rbinfo = "线上"

            else:
                self.tokenurl = "http://11.2.77.3:30089/portal-test/user/login/account"
                self.upfileurl = "http://11.2.77.3:30089/portal-test/store/file/upload"
                self.useridurl = "http://11.2.77.3:30089/portal-test/user/person/get"
                self.changepemurl = "http://11.2.77.3:30089/portal-test/store/file/merge"

    def initUi4(self):
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('CASJC')

        formlayout = QFormLayout()

        fileup = QLabel("文件上传")
        self.filebutton = QPushButton("选择文件", self)

        self.filebutton.clicked.connect(self.selefile)

        self.show()

    def selefile(self):
        self.file_up, self.bbb = QFileDialog.getOpenFileName(
            self, "打开文件", os.getcwd(), "All File(*)")
        p, self.filename_up = os.path.split(self.file_up)
        #print(self.filename_up)
        try:
            self.selefilenameup.setVisible(False)
        except:
            pass
        self.selefile = QLabel("选中文件")
        self.selefilename = QLabel(self.filename_up)

        self.jindu = QLabel("进度条")
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)

        self.btn = QPushButton('开始上传', self)
        self.btn.move(40, 80)

        self.formlayout.addRow(self.selefile, self.selefilename)
        self.formlayout.addRow(self.jindu, self.pbar)
        self.formlayout.addRow(self.btn)
        self.btn.clicked.connect(self.cmd)

        self.timer = QBasicTimer()
        self.step = 0
        self.setGeometry(300, 300, 320, 200)

    def submitStore(self):
        print(self.nameLineEdit.text())
        print(self.introductionLineEdit.text())
        print(self.filename_up)

    def timerEvent(self, e):

        if self.step >= 100:
            self.step = 0
            self.pbar.setValue(self.step)
            self.timer.stop()
            self.btn.setText('完成')
            return
        #self.step = self.step+1
        #self.pbar.setValue(self.step)

    def cmd(self):
        print("do action")
        self.btn.setEnabled(False)
        if self.timer.isActive():
            self.timer.stop()
            self.btn.setText('开始')
        else:
            self.timer.start(100, self)
            self.btn.setText('上传中')
        print(self.username)
        self.userid = self.getuserId()
        print("文件名: " + self.filename_up)
        #文件大小
        self.ffsize = os.path.getsize(self.file_up)
        print("文件大小: " + str(self.ffsize))
        #文件分片块数
        self.totalchunk = int(self.ffsize / self.kuaidx) + 1
        print("文件块数: " + str(self.totalchunk))
        #self.work.start()

        #shangchuang = dfThread(self.ffsize,self.totalchunk,self.username,self.userid,self.file_up,self.filename_up, self.step)
        #shagnchuang.start()

        self.filerun(self.ffsize, self.totalchunk, self.username, self.userid)

        self.merge()
        print("ok")
        self.selefile.setVisible(False)
        self.selefilename.setVisible(False)
        self.pbar.setVisible(False)
        self.jindu.setVisible(False)
        self.btn.setVisible(False)
        self.selefilenameup = QLabel("文件:" + self.filename_up + " 上传完成")
        self.formlayout.addRow(self.selefilenameup)
        #self.btn.setEnabled(True)

    def execute(self):
        self.work.start()
        self.work.trigger.connect(self.display)

    def display(self):
        self.listWidget.addItem(str)

    def Casjc_login(self):
        self.username = self.nameLineEdit.text()
        #print(self.introductionLineEdit.text())
        url = self.tokenurl
        header = {}
        header['Content-Type'] = "application/json"
        data = {}
        data["account"] = self.nameLineEdit.text()
        data["password"] = self.introductionLineEdit.text()
        data["rememberMe"] = False
        data["origin"] = 0
        try:
            r = requests.post(url, headers=header, data=json.dumps(data))
            if r.status_code == 200:
                if r.json()['code'] == 200:
                    print(r.json()['data'])
                    self.login_session = r.json()['data']
                    self.login_mess = '登录成功'
                    self.nameLabel.setVisible(False)
                    self.nameLineEdit.setVisible(False)
                    self.introductionLabel.setVisible(False)
                    self.introductionLineEdit.setVisible(False)
                    self.bt1.setVisible(False)
                    self.rb1.setVisible(False)
                    self.rb2.setVisible(False)
                    #self.bt2 = QPushButton('退出',self)
                    #self.bt2.setGeometry(200,200,30,20)
                    self.lab = QLabel(self.rbinfo, self)
                    self.fileup = QLabel("文件上传")
                    self.filebutton = QPushButton("选择文件", self)
                    self.colonyId = QLabel("colonyId")
                    self.mycolonyId = QLineEdit("43")
                    self.colonypath = QLabel("路径")
                    self.mycolonypath = QLineEdit("/public1")
                    self.formlayout.addRow(self.lab)
                    self.formlayout.addRow(self.colonyId, self.mycolonyId)
                    self.formlayout.addRow(self.colonypath, self.mycolonypath)
                    self.formlayout.addRow(self.fileup, self.filebutton)
                    self.filebutton.clicked.connect(self.selefile)
                    #self.bt2 = QPushButton('退出',self)
                    #self.bt2.setGeometry(155,150,60,40)
                else:
                    print('登录认证信息错误')
                    self.login_mess = '登录认证信息错误'
            else:
                print('登录异常')
                self.login_mess = '登录异常'
        except requests.exceptions.ConnectionError:
            print("网络异常无法连接服务器")
            self.login_mess = '网络异常无法连接服务器'
        except requests.exceptions.MissingSchema:
            print('请求的Url地址有误')
            self.login_mess = '请求的Url地址有误'
        except requests.exceptions.Timeout as e:
            print('请求超时:' + str(e.message))
            self.login_mess = '请求超时'
        except requests.exceptions.HTTPError as e:
            print('http请求错误:' + str(e.message))
            self.login_mess = 'http请求错误'
        reply = QMessageBox.information(self, "登录提示信息", self.login_mess,
                                        QMessageBox.Yes)

        #self.setLayout(self.formlayout)

    def getuserId(self):
        url = self.useridurl
        header = {}
        header["Authorization"] = self.login_session
        header['Token'] = self.login_session
        header['Cookie'] = "JSESSIONID=" + self.login_session
        r = requests.get(url, headers=header)
        #print(r.content)
        print(r.json()['data']['id'])
        return r.json()['data']['id']

    def filerun(self, ffsize, totalchunk, username, userid):
        #文件md5值
        self.ident = cmd5(self.file_up)
        with open(self.file_up, 'rb') as f:
            chunknumber = 0
            for chunk in iter(lambda: f.read(self.kuaidx), b''):
                chunknumber += 1
                print("当前块编号:" + str(chunknumber))
                #md5 = hashlib.md5()
                #print(f.tell())
                #md5.update(chunk)
                if len(chunk) < self.kuaidx:
                    kuaisj = len(chunk)
                else:
                    kuaisj = self.kuaidx
                print(len(chunk))
                #chunkmd5 = md5.hexdigest()
                #print(chunkmd5)
                while True:
                    if self.upfile2(chunknumber, kuaisj, ffsize, totalchunk,
                                    chunk, username, userid):
                        self.step = self.step + (100 / self.totalchunk)
                        self.pbar.setValue(self.step)
                        break
                    else:
                        time.sleep(3)

    def upfile2(self, chunknumber, cchunksize, totalsize, totalchunk, chunk,
                username, userid):
        url = self.upfileurl
        header = {}
        header['Token'] = self.login_session
        dd = {}
        dd['chunkNumber'] = (None, chunknumber)
        dd['chunkSize'] = (None, self.kuaidx)
        dd['currentChunkSize'] = (None, cchunksize)
        dd['totalSize'] = (None, totalsize)
        dd['identifier'] = (None, self.ident)
        dd['filename'] = (None, self.filename_up)
        dd['relativePath'] = (None, self.filename_up)
        dd['totalChunks'] = (None, totalchunk)
        dd['accept'] = (None, "*")
        dd['userId'] = (None, userid)
        dd['colonyId'] = (None, self.mycolonyId.text())
        dd['toPath'] = (None, "/")
        dd['userHomeDir'] = (None, self.mycolonypath.text())
        dd['upfile'] = (self.filename_up, chunk)
        #print(dd)
        try:
            r = requests.post(url, headers=header, files=dd)
            print(r.content)
            if r.json()['code'] == 200:
                return 1
            return None
        except requests.exceptions.Timeout as e:
            print('请求超时:' + str(e.message))
        except requests.exceptions.HTTPError as e:
            print('http请求错误:' + str(e.message))
        except requests.exceptions.ConnectionError:
            print('网卡断了')

    def merge(self):
        url = self.changepemurl
        header = {}
        header['Token'] = self.login_session
        header['Content-Type'] = "application/json"
        dd = {}
        dd['colonyId'] = self.mycolonyId.text()
        dd['filename'] = self.filename_up
        dd['identifier'] = self.ident
        dd['isFolder'] = False
        dd['toPath'] = "/"
        dd['totalSize'] = self.ffsize
        dd['totalChunks'] = self.totalchunk
        dd['relativePath'] = self.filename_up
        dd['userHomeDir'] = self.mycolonypath.text()
        dd['userId'] = self.userid
        print(dd['userHomeDir'])
        print(header)
        r = requests.post(url, headers=header, data=json.dumps(dd))
        print(r.content)
        print(r.json())
예제 #22
0
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        btn1 = QPushButton('&Button1', self)
        btn1.setCheckable(True)
        btn1.toggle()

        btn2 = QPushButton(self)
        btn2.setText('Button&2')

        btn3 = QPushButton('Button3', self)
        btn3.setEnabled(False)

        #label
        label = QLabel('나는 라벨', self)
        label.setAlignment(Qt.AlignCenter)
        font = label.font()
        font.setPointSize(10)
        font.setFamily('Times New Roman')
        font.setBold(True)
        label.setFont(font)

        #QCheckBox
        cb = QCheckBox('Show title', self)
        cb.move(20, 20)
        cb.toggle()
        #cb.stateChanged.connect(self.changeTitle)
        #여기선 제목을 바꿀 수 없는듯

        rbtn1 = QRadioButton('동구란 버튼', self)
        rbtn1.setChecked(True)
        rbtn2 = QRadioButton(self)
        rbtn2.setText('도옹구란 버튼')

        #ComboBox 생성
        #self.lbl = QLabel('Option1', self)
        cob = QComboBox(self)
        cob.addItem('Option1')
        cob.addItem('Option2')
        cob.addItem('Option3')
        cob.addItem('Option4')
        #cob.activated[str].connect(self.onActivated)

        #LineEdit 생성
        qle = QLineEdit(self)
        #qle.textChanged[str].connect(self.onChanged)

        #ProgressBar 진행상황 막대기
        self.pbar = QProgressBar(self)
        #self.pbar.setGeometry(30, 40, 200, 25)

        self.btnS = QPushButton('Start', self)
        self.btnS.clicked.connect(self.doAction)

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

        #QSlider, QDial
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(0, 50)
        self.slider.setSingleStep(2)
        self.dial = QDial(self)
        self.dial.setRange(0, 50)
        self.slider.valueChanged.connect(self.dial.setValue)
        self.dial.valueChanged.connect(self.slider.setValue)

        pixmap = QPixmap('Hanabi.PNG')

        lbl_img = QLabel()
        lbl_img.setPixmap(pixmap)
        lbl_size = QLabel('Width: ' + str(pixmap.width()) + ', Height: ' +
                          str(pixmap.height()))
        lbl_size.setAlignment(Qt.AlignCenter)

        self.lbl1 = QLabel('QSpinBox')
        self.spinbox = QSpinBox()
        self.spinbox.setMinimum(-10)
        self.spinbox.setMaximum(30)
        self.spinbox.setSingleStep(2)
        self.lbl2 = QLabel('0')

        self.spinbox.valueChanged.connect(self.value_changed)

        #doubleSpinBox
        self.lbl3 = QLabel('QDoubleSpinBox')
        self.dspinbox = QDoubleSpinBox()
        self.dspinbox.setRange(0, 100)
        self.dspinbox.setSingleStep(0.5)
        self.dspinbox.setPrefix('$ ')
        self.dspinbox.setDecimals(1)
        self.lbl4 = QLabel('$ 0.0')

        self.dspinbox.valueChanged.connect(self.value_changed)

        layout1 = QHBoxLayout()
        layout2 = QHBoxLayout()
        layout3 = QHBoxLayout()
        layout4 = QHBoxLayout()
        layout5 = QHBoxLayout()

        vlayout = QVBoxLayout()
        vlayout2 = QVBoxLayout()

        layout1.addWidget(btn1)
        layout1.addWidget(btn2)
        layout1.addWidget(cob)

        layout2.addWidget(label)
        layout2.addWidget(cb)
        layout2.addWidget(rbtn1)
        layout2.addWidget(rbtn2)

        layout3.addWidget(btn3)
        layout3.addWidget(qle)

        layout4.addWidget(self.slider)
        layout4.addWidget(self.dial)

        vlayout2.addWidget(self.lbl1)
        vlayout2.addWidget(self.spinbox)
        vlayout2.addWidget(self.lbl2)
        vlayout2.addWidget(self.lbl3)
        vlayout2.addWidget(self.dspinbox)
        vlayout2.addWidget(self.lbl4)

        layout5.addWidget(lbl_img)
        layout5.addLayout(vlayout2)

        vlayout.addLayout(layout1)
        vlayout.addLayout(layout3)
        vlayout.addLayout(layout2)
        vlayout.addWidget(self.pbar)
        vlayout.addWidget(self.btnS)
        vlayout.addLayout(layout4)
        vlayout.addLayout(layout5)
        self.setLayout(vlayout)

    def value_changed(self):
        self.lbl2.setText(str(self.spinbox.value()))

    def onActivated(self, text):
        self.lbl.setText(text)
        self.lbl.adjustSize()

    def onChanged(self, text):
        self.lbl.setText(text)
        self.lbl.adjustSize()

    def timerEvent(self, e):
        if self.step >= 100:
            self.timer.stop()
            self.btnS.setText('Finished')
            return

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

    def doAction(self):
        if self.timer.isActive():
            self.timer.stop()
            self.btnS.setText('Start')
        else:
            self.timer.start(100, self)
            self.btnS.setText('Stop')
예제 #23
0
class myMainWindow(QMainWindow, Ui_MainWindow, QScrollArea):
    def __init__(self):
        super().__init__()
        self.setAcceptDrops(True)
        self.setupUi(self)
        '''
        以下是各按键与各函数的绑定
        '''
        #数据初始化
        self.orignal_df = None
        self.tempDF = None
        #异常模块窗口初始化信息
        self.modelseted = False
        #数据摘要窗口初始化信息
        self.tableViewSeted = False
        self.setFixedSize(1068, 737)
        self.setWindowTitle('Data Visualization')
        self.setWindowIcon(
            QIcon(r'Z:\Data_Visualization\venv\qrc\icons\icon.png'))

        #self.progressBar.hide()
        #openfile键与获取文件信息并展示函数的绑定
        self.actionOpen_file.triggered.connect(self.getFile_toShow)
        #save as csv file键与函数save as csv 文件的绑定
        self.actionas_a_Csv_File.triggered.connect(self.File_save_as_csv)
        #save as excel file 与 函数save as execl文件的绑定
        self.actionas_a_Excel_file.triggered.connect(self.File_save_as_excel)
        #退出键
        self.actionExit.triggered.connect(self.close)
        #删除所有问题行操作键与相关函数的绑定
        self.actionDelete_problematic_rows.triggered.connect(
            self.Quick_Operation_delete_rows)
        #删除所有问题列操作键与相关函数的绑定
        self.actionDelete_problematic_columns.triggered.connect(
            self.Quick_Operation_delete_cols)
        #删除重复值操作键与相关函数的绑定
        self.actionDelete_duplicate_values.triggered.connect(
            self.Quick_Operation_delete_duplicate_values)
        #刷新所有窗口数据操作键与其相关函数的绑定
        self.actionUpdating_all_the_Windows.triggered.connect(
            self.Updating_all_windows)
        #填充空缺值操作
        self.actionFill_problematic_columns_with.triggered.connect(
            self.FillnaWith)
        #强制类型转换与相关ui界面的绑定
        self.actionForced_type_Conversion.triggered.connect(
            self.Forced_type_conversion)
        #筛选操作的绑定
        self.actionread_only.triggered.connect(self.Selection_read_only)
        #筛选操作并替换原来的数据
        self.actioninplace.triggered.connect(self.Selection_inplace)
        #科学计算add与相关ui界面的绑定
        self.actionadd.triggered.connect(self.Scientific_add)
        #科学计算radd与相关ui界面的绑定
        self.actionradd.triggered.connect(self.Scientific_radd)
        #科学计算sub与相关ui界面的绑定
        self.actionsub.triggered.connect(self.Scientific_sub)
        #科学计算rsub与相关ui界面的绑定
        self.actionrsub.triggered.connect(self.Scientific_rsub)
        #科学计算div与相关ui界面的绑定
        self.actiondiv.triggered.connect(self.Scientific_div)
        #科学计算rdiv与相关ui界面的绑定
        self.actionrdiv.triggered.connect(self.Scientific_rdiv)
        #科学计算floordiv与相关ui界面的绑定
        self.actionfloordiv.triggered.connect(self.Scientific_floordiv)
        #科学计算rfloordiv与相关ui界面的绑定
        self.actionrfloordiv.triggered.connect(self.Scientific_rfloordiv)
        #科学计算pow与相关ui界面的绑定
        self.actionpow.triggered.connect(self.Scientific_pow)
        #科学计算rpow与相关ui界面的绑定
        self.actionrpow.triggered.connect(self.Scientific_rpow)
        #相关系数计算
        self.actioncorr.triggered.connect(self.Scientific_corr)
        #cov
        self.actioncov.triggered.connect(self.Scientific_cov)
        #绘画函数plot与相关函数绑定
        self.actionplot.triggered.connect(self.Matplotlib_plot)
        #散点图
        self.actionscatter.triggered.connect(self.Matplotlib_scatter)
        #饼图
        self.actionpie.triggered.connect(self.Matplotlib_pie)
        #柱状图
        self.actionbar.triggered.connect(self.Matplotlib_bar)
        #水平柱状图
        self.actionbarh.triggered.connect(self.Matplotlib_barh)
        #直方图
        self.actionhist.triggered.connect(self.Matplotlib_hist)

        #self.orignal_df[i[0]] = to_datetime(self.orignal_df[i[0]], errors='ignore', format=self.formatStr)

    def Forced_type_conversion(self):
        if self.orignal_df is not None:
            self.ui = myTypeConversion(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(self.Forced_type_conversion_recive)

    def Forced_type_conversion_recive(self, data):

        #print(data)
        try:
            for i in data:
                self.orignal_df[i[0]] = self.orignal_df[i[0]].astype(
                    info[i[1]], errors='ignore')
            self.Updating_all_windows()

        except:
            QMessageBox.information(self, '提示', '类型转换不支持', QMessageBox.Yes)
        #print('end')
        #print(self.orignal_df.dtypes)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()

    def closeEvent(self, *args, **kwargs):
        try:
            self.ui.close()
        except:
            pass
        finally:
            self.close()

    def dropEvent(self, event):
        filename = event.mimeData().urls()[0].path()[1:]
        #print(filename)
        if filename[-4:] == '.csv' or filename[-4:] == 'xlsx' or filename[
                -4:] == '.xls':
            self.thread0 = File_read_thread(filename)
            # 线程0文件读取完毕发送信号与receive以及viewFile函数绑定
            self.thread0.fileReadDone[type(DataFrame())].connect(self.receive)
            self.thread0.fileReadDone[type(DataFrame())].connect(self.viewFile)
            self.thread0.start()
            self.timer = QBasicTimer()
            self.step = 0
            self.progressBar = QProgressDialog(self)
            self.progressBar.setCancelButton(None)
            #self.progressBar.setWindowFlags(Qt.WindowCloseButtonHint)
            self.progressBar.setWindowModality(Qt.WindowModal)
            self.progressBar.setWindowTitle('文件读取中...')
            self.progressBar.setLabelText('解析进行中,请稍候...')
            self.progressBar.setRange(0, 100)
            self.progressBar.show()
            if self.timer.isActive():
                self.timer.stop()
                self.step = 0
            else:
                self.step = 0
                self.timer.start(100, self)

        else:
            QMessageBox.warning(self, 'warning!', '文件格式不支持', QMessageBox.Yes,
                                QMessageBox.Yes)

    def receive(self, df):
        '''
        接收线程发送的文件信息
        :return:
        '''
        #self.orignal_df = self.thread0.df
        self.orignal_df = df
        self.progressBar.setValue(300)
        self.timer.stop()
        self.progressBar.close()

    def Temp_data_init(self):
        self.tempDF = None

    def data_recovery(self):
        if self.tempDF is not None:
            self.orignal_df = self.tempDF
            self.tempDF = None
            self.Updating_all_windows()

    def Fillna_data_recive(self, data):
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            if i[1] == 'Null':
                self.orignal_df[i[0]].fillna(Numbertic(i[2]), inplace=True)
                self.Updating_all_windows()
            else:
                if i[1] == 'mean':
                    self.orignal_df[i[0]].fillna(self.orignal_df[i[0]].mean(),
                                                 inplace=True)
                    self.Updating_all_windows()
                elif i[1] == 'median':
                    self.orignal_df[i[0]].fillna(
                        self.orignal_df[i[0]].median(), inplace=True)
                    self.Updating_all_windows()
                elif i[1] == 'max':
                    self.orignal_df[i[0]].fillna(self.orignal_df[i[0]].max(),
                                                 inplace=True)
                    self.Updating_all_windows()
                elif i[1] == 'min':
                    self.orignal_df[i[0]].fillna(self.orignal_df[i[0]].min(),
                                                 inplace=True)
                    self.Updating_all_windows()

    def Scientific_add(self):
        if self.orignal_df is not None:
            self.ui = myAdd(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(self.Scientific_data_add_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_add_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].add(Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_radd(self):
        if self.orignal_df is not None:
            self.ui = myrAdd(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(self.Scientific_data_radd_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_radd_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].radd(Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_sub(self):
        if self.orignal_df is not None:
            self.ui = mySub(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(self.Scientific_data_sub_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_sub_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].sub(Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_rsub(self):
        if self.orignal_df is not None:
            self.ui = myrSub(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(self.Scientific_data_rsub_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_rsub_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].rsub(Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_div(self):
        if self.orignal_df is not None:
            self.ui = myDiv(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(self.Scientific_data_div_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_div_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].div(Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_rdiv(self):
        if self.orignal_df is not None:
            self.ui = myrDiv(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(self.Scientific_data_rdiv_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_rdiv_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].rdiv(Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_floordiv(self):
        if self.orignal_df is not None:
            self.ui = myFloordiv(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(
                self.Scientific_data_floordiv_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_floordiv_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].floordiv(
                Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_rfloordiv(self):
        if self.orignal_df is not None:
            self.ui = myrFloordiv(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(
                self.Scientific_data_rfloordiv_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_rfloordiv_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].rfloordiv(
                Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_pow(self):
        if self.orignal_df is not None:
            self.ui = myPow(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(self.Scientific_data_pow_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_pow_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].pow(Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_rpow(self):
        if self.orignal_df is not None:
            self.ui = myrPow(self.orignal_df)
            self.ui.show()
            self.ui.okButtonPressed.connect(self.Scientific_data_rpow_recive)
            self.ui.applyButtonPressed.connect(self.Temp_data_init)
            self.ui.cancalButtonPressed.connect(self.data_recovery)

    def Scientific_data_rpow_recive(self, data):
        #print(data)
        if self.tempDF is None:
            self.tempDF = self.orignal_df.copy()
        for i in data:
            self.orignal_df[i[0]] = self.orignal_df[i[0]].rpow(Numbertic(i[1]))
        self.Updating_all_windows()

    def Scientific_data_corr_recive(self, data):
        #print(data)
        result = self.orignal_df.corr(data[0])
        self.ui = Corr_show(result)
        self.ui.show()

    def Scientific_corr(self):
        if self.orignal_df is not None:
            self.ui = myCorr()
            self.ui.show()
            self.ui.window.connect(self.Scientific_data_corr_recive)

    def Scientific_cov(self):
        if self.orignal_df is not None:
            result = self.orignal_df.cov()
            self.ui = Cov_show(result)
            self.ui.show()

    def Selection_data_recive(self, data):
        '''

        :param data: 返回操作信息
        :return: None
        '''
        #判空操作,若非空则执行
        #print(data)

        tempData = []  #各逻辑操作返回的数据集
        for i in data:
            tempData.append(sih(self.orignal_df, i))
        #对数据集进行取交集操作
        #print(tempData)
        try:
            if type(str()) in list(map(type, tempData)):
                ok = QMessageBox.warning(self.ui, 'waring', '参数错误,\n请检查输入的参数。',
                                         QMessageBox.Yes | QMessageBox.Yes,
                                         QMessageBox.No)
                if ok:
                    self.ui.settableWidget()
            else:
                if len(tempData) == 1 and tempData[0].empty:
                    QMessageBox.information(self, '提示', '数据集为空',
                                            QMessageBox.Yes, QMessageBox.Yes)

                elif len(tempData) == 1 and not tempData[0].empty:
                    if type(self.tempDF) is type(None):
                        self.tempDF = self.orignal_df
                        self.orignal_df = tempData[0]
                        self.Updating_all_windows()
                    else:
                        self.orignal_df = tempData[0]
                        self.Updating_all_windows()

                else:
                    if type(self.tempDF) is type(None):
                        self.tempDF = self.orignal_df
                    if True in list(map(lambda x: x.empty, tempData)):
                        #print(list(map(lambda x:x.empty,tempData)))
                        QMessageBox.information(self, '提示', '数据集为空',
                                                QMessageBox.Yes,
                                                QMessageBox.Yes)
                    else:
                        for i in range(len(tempData) - 1):
                            self.orignal_df = merge(tempData[i],
                                                    tempData[i + 1],
                                                    how='inner')
                        if self.orignal_df.empty:
                            QMessageBox.information(self, '提示', '数据集为空',
                                                    QMessageBox.Yes,
                                                    QMessageBox.Yes)
                        else:
                            self.Updating_all_windows()

        except Exception as e:
            QMessageBox.warning(self.ui, 'waring', str(e.args),
                                QMessageBox.Yes, QMessageBox.Yes)

    def Selection_inplace(self):
        if self.orignal_df is not None:
            self.ui = mySelection(self.orignal_df)
            self.ui.show()
            self.ui.SelectionSignal[type(list())].connect(
                self.Selection_data_recive)

    def FillnaWith(self):
        if self.orignal_df is None:
            QMessageBox.information(self, '提示', '未读取数据', QMessageBox.Yes,
                                    QMessageBox.Yes)

        else:
            self.ui = myFillnaWith(self.orignal_df)
            if len(self.ui.columns) == 0:
                QMessageBox.information(self, '提示', '数据不存在异常值',
                                        QMessageBox.Yes, QMessageBox.Yes)
                self.ui.close()
            else:
                self.ui.show()
                self.ui.FillNaSignal.connect(self.Fillna_data_recive)
                self.ui.CancalButtonPressed.connect(self.data_recovery)
                self.ui.ExitButtonPressed.connect(self.Temp_data_init)

    def Selection_read_only(self):
        if self.orignal_df is not None:
            self.ui = mySelection(self.orignal_df)
            self.ui.show()
            self.ui.SelectionSignal[type(list())].connect(
                self.Selection_data_recive)
            self.ui.closeButtonPressed.connect(self.data_recovery)

    def timerEvent(self, *args, **kwargs):
        self.progressBar.setValue(self.step)
        if self.step >= 100:
            self.timer.stop()
            self.step = 0
            return
        elif self.step < 99:
            self.step += 1

    def getFile_toShow(self):
        '''
        获取文件信息并显示
        :return:
        '''

        FileName = QFileDialog.getOpenFileName(
            filter="Data file(*.csv *.xlsx *.xls)")
        #print(FileName)
        #print(FileName[0])
        if FileName[0] != '':
            self.thread0 = File_read_thread(FileName[0])
            #线程0文件读取完毕发送信号与receive以及viewFile函数绑定
            self.thread0.fileReadDone[type(DataFrame())].connect(self.receive)
            self.thread0.fileReadDone[type(DataFrame())].connect(self.viewFile)
            self.thread0.start()
            self.timer = QBasicTimer()
            self.step = 0
            self.progressBar = QProgressDialog(self)
            self.progressBar.setCancelButton(None)
            #self.progressBar.setWindowFlags(Qt.WindowCloseButtonHint)
            self.progressBar.setWindowModality(Qt.WindowModal)
            self.progressBar.setWindowTitle('文件读取中...')
            self.progressBar.setLabelText('解析进行中,请稍候...')
            self.progressBar.setRange(0, 100)
            self.progressBar.show()
            if self.timer.isActive():
                self.timer.stop()
                self.step = 0
            else:
                self.step = 0
                self.timer.start(100, self)

    def viewFile(self):
        '''
        展示文件的函数
        :return:
        '''
        if self.orignal_df.empty:
            QMessageBox.warning(self, '警告', '文件为空文件!', QMessageBox.Yes,
                                QMessageBox.Yes)
        self.ErrorDataview_show()
        self.tableView_show()
        self.label_2.close()
        self.widget = self.pandastablewidget
        self.model = DataFrameModel()
        self.widget.setViewModel(self.model)
        self.model.setDataFrame(self.orignal_df)

    def File_save_as_csv(self):
        '''
        文件保存为csv文件
        :return:
        '''
        if self.orignal_df is None:
            QMessageBox.information(self, '提示', '未读取文件', QMessageBox.Yes,
                                    QMessageBox.Yes)
        else:
            FileName = QFileDialog.getSaveFileUrl(filter="Data file(*.csv )")
            print(str(FileName[0].toString())[8:])
            if str(FileName[0].toString()) != '':
                try:
                    self.thread2 = File_Save_as_csv(
                        self.orignal_df,
                        str(FileName[0].toString())[8:])
                    self.thread2.start()
                except Exception as e:
                    QMessageBox.information(self, '提示', '文件保存失败!',
                                            QMessageBox.Yes, QMessageBox.Yes)
            #text, ok = QInputDialog.getText(self, 'save as csv', '请输入文件名称')
            #if ok:
            #FileName = text + '.csv'
            #self.thread2 = File_Save_as_csv(self.orignal_df, FileName)
            #self.thread2.start()
    def File_save_as_excel(self):
        '''
        文件保存为excel文件
        :return:
        '''
        if self.orignal_df is None:
            QMessageBox.information(self, '提示', '未读取文件', QMessageBox.Yes,
                                    QMessageBox.Yes)
        else:
            FileName = QFileDialog.getSaveFileUrl(
                filter="Data file(*.xls *xlsx)")
            #print(str(FileName[0].toString())[8:])
            if str(FileName[0].toString()) != '':
                try:
                    self.thread2 = File_Save_as_excel(
                        self.orignal_df,
                        str(FileName[0].toString())[8:])
                    self.thread2.start()
                except Exception as e:
                    QMessageBox.information(self, '提示', '文件保存失败!',
                                            QMessageBox.Yes, QMessageBox.Yes)

    def tableView_show(self):
        '''
        数据摘要显示
        :return:
        '''
        if not self.orignal_df.empty:
            self.tableViewSeted = True
            col, row = self.orignal_df.describe().shape
            self.tableView.model = QStandardItemModel(col, row)
            self.tableView.model.setHorizontalHeaderLabels(
                list(self.orignal_df.describe().columns))
            self.tableView.model.setVerticalHeaderLabels(
                list(self.orignal_df.describe().index))
            self.tableView.setModel(self.tableView.model)
            self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
            self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
            #self.tableView.horizontalHeader().setStretchLastSection(True)
            #self.tableView.verticalHeader().setStretchLastSection(True)
            index_x = 0
            for row in self.orignal_df.describe().iteritems():
                index_x += 1
                index_y = 0
                for s in list(row[1]):
                    index_y += 1
                    newItem = QStandardItem(str(s))
                    self.tableView.model.setItem(index_y - 1, index_x - 1,
                                                 newItem)
        elif self.orignal_df.empty and self.tableViewSeted == True:
            self.tableView.model.clear()

    def ErrorDataview_show(self):

        if not self.orignal_df[self.orignal_df.isnull().values ==
                               True].empty and not self.orignal_df.empty:
            self.modelseted = True
            data = self.orignal_df[self.orignal_df.isnull().values == True]
            col, row = data.shape
            self.tableView_2.model = QStandardItemModel(col, row)
            self.tableView_2.model.setHorizontalHeaderLabels(list(
                data.columns))
            self.tableView_2.model.setVerticalHeaderLabels(
                list((map(str, data.index))))
            self.tableView_2.setModel(self.tableView_2.model)
            self.tableView_2.setEditTriggers(QAbstractItemView.NoEditTriggers)
            self.tableView_2.setSelectionBehavior(QAbstractItemView.SelectRows)
            #self.tableView_2.horizontalHeader().setStretchLastSection(True)
            #self.tableView_2.verticalHeader().setStretchLastSection(True)

            index_x = 0
            for row in data.iteritems():
                index_x += 1
                index_y = 0
                for s in list(row[1]):
                    index_y += 1
                    newItem = QStandardItem(str(s))
                    self.tableView_2.model.setItem(index_y - 1, index_x - 1,
                                                   newItem)
        elif self.orignal_df.empty and self.modelseted == True:
            self.tableView_2.model.clear()
        elif self.orignal_df[self.orignal_df.isnull().values ==
                             True].empty and not self.orignal_df.empty:
            if self.modelseted == True:
                self.tableView_2.model.clear()
            else:
                pass

    def Quick_Operation_delete_rows(self):
        if self.orignal_df is None:
            QMessageBox.information(self, '提示', '未读取数据', QMessageBox.Yes,
                                    QMessageBox.Yes)
        else:
            self.orignal_df = self.orignal_df.dropna()
            self.Updating_all_windows()

    def Quick_Operation_delete_cols(self):
        if self.orignal_df is None:
            QMessageBox.information(self, '提示', '未读取数据', QMessageBox.Yes,
                                    QMessageBox.Yes)
        else:
            self.orignal_df = self.orignal_df.dropna(axis=1)
            self.Updating_all_windows()

    def Quick_Operation_delete_duplicate_values(self):
        if self.orignal_df is None:
            QMessageBox.information(self, '提示', '未读取数据', QMessageBox.Yes,
                                    QMessageBox.Yes)
        else:
            self.orignal_df = self.orignal_df.drop_duplicates()
            self.Updating_all_windows()

    def Updating_all_windows(self):
        if self.orignal_df is None:
            QMessageBox.information(self, '提示', '未读取数据', QMessageBox.Yes,
                                    QMessageBox.Yes)
        else:
            self.ErrorDataview_show()
            self.tableView_show()
            self.widget = self.pandastablewidget
            self.model = DataFrameModel()
            self.widget.setViewModel(self.model)
            self.model.setDataFrame(self.orignal_df)

    def Matplotlib_plot_show(self, data):
        self.ui = QmyMainWindow(data[0], data[1], data[2])
        self.ui.show()

    def Matplotlib_plot(self):
        if self.orignal_df is not None:
            self.ui = Dia(self.orignal_df[self.orignal_df.describe().columns])
            self.ui.show()
            self.ui.window.connect(self.Matplotlib_plot_show)

    def Matplotlib_scatter_show(self, data):
        self.ui = QmyMainWindow1(data[0], data[1], data[2])
        self.ui.show()

    def Matplotlib_scatter(self):
        if self.orignal_df is not None:
            self.ui = Dia1(self.orignal_df[self.orignal_df.describe().columns])
            self.ui.show()
            self.ui.window.connect(self.Matplotlib_scatter_show)

    def Matplotlib_pie_show(self, data):
        #print(data)
        self.ui = QmyMainWindow2(data[0], data[1], data[2], data[3], data[4],
                                 self.orignal_df)
        self.ui.show()

    def Matplotlib_pie(self):
        if self.orignal_df is not None:
            self.ui = Dia2(self.orignal_df)
            self.ui.show()
            self.ui.window.connect(self.Matplotlib_pie_show)

    def Matplotlib_bar_show(self, data):
        #print(data)
        self.ui = QmyMainWindow3(data, self.orignal_df)
        self.ui.show()

    def Matplotlib_bar(self):
        if self.orignal_df is not None:
            self.ui = Dia3(self.orignal_df)
            self.ui.show()
            self.ui.window.connect(self.Matplotlib_bar_show)

    def Matplotlib_barh_show(self, data):
        #print(data)
        if self.orignal_df is not None:
            self.ui = QmyMainWindow4(data, self.orignal_df)
            self.ui.show()

    def Matplotlib_barh(self):
        if self.orignal_df is not None:
            self.ui = Dia4(self.orignal_df)
            self.ui.show()
            self.ui.window.connect(self.Matplotlib_barh_show)

    def Matplotlib_hist_show(self, data):
        #print(data)
        if self.orignal_df is not None:
            self.ui = QmyMainWindow5(data, self.orignal_df)
            self.ui.show()

    def Matplotlib_hist(self):
        if self.orignal_df is not None:
            self.ui = Dia5(self.orignal_df)
            self.ui.show()
            self.ui.window.connect(self.Matplotlib_hist_show)
예제 #24
0
class MainBoard(QFrame):
    msg = pyqtSignal(str)
    BoardWidth = 10
    BoardHeight = 20
    Speed = 300

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

    def initBoard(self):
        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):
        return self.board[(y * MainBoard.BoardWidth) + x]

    def setShapeAt(self, x, y, shape):
        self.board[(y * MainBoard.BoardWidth) + x] = shape

    def squareWidth(self):
        return self.contentsRect().width() // MainBoard.BoardWidth

    def squareHeight(self):
        return self.contentsRect().height() // MainBoard.BoardHeight

    def start(self):
        if self.isPaused:
            return
        self.isStarted = True
        self.isWaitingAfterLine = False
        self.numLinesRemoved = 0
        self.clearBoard()
        self.msg.emit(str(self.numLinesRemoved))
        self.newPiece()
        self.timer.start(MainBoard.Speed, self)

    def pause(self):
        if not self.isStarted:
            return
        self.isPaused = not self.isPaused
        if self.isPaused:
            self.timer.stop()
            self.msg.emit("paused")
        else:
            self.timer.start(MainBoard.Speed, self)
            self.msg.emit(str(self.numLinesRemoved))
        self.update()

    def paintEvent(self, event):
        painter = QPainter(self)
        rect = self.contentsRect()
        boardTop = rect.bottom() - MainBoard.BoardHeight * self.squareHeight()
        for i in range(MainBoard.BoardHeight):
            for j in range(MainBoard.BoardWidth):
                shape = self.shapeAt(j, MainBoard.BoardHeight - i - 1)
                if shape != ShapeForm.NoShape:
                    self.drawSquare(painter,
                                    rect.left() + j * self.squareWidth(),
                                    boardTop + i * self.squareHeight(), shape)
        if self.curPiece.shape() != ShapeForm.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 +
                    (MainBoard.BoardHeight - y - 1) * self.squareHeight(),
                    self.curPiece.shape())

    def keyPressEvent(self, event):
        if not self.isStarted or self.curPiece.shape() == ShapeForm.NoShape:
            super(MainBoard, 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(MainBoard, self).keyPressEvent(event)

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            if self.isWaitingAfterLine:
                self.isWaitingAfterLine = False
                self.newPiece()
            else:
                self.oneLineDown()
        else:
            super(MainBoard, self).timerEvent(event)

    def clearBoard(self):
        for i in range(MainBoard.BoardHeight * MainBoard.BoardWidth):
            self.board.append(ShapeForm.NoShape)

    def dropDown(self):
        newY = self.curY
        while newY > 0:
            if not self.tryMove(self.curPiece, self.curX, newY - 1):
                break
            newY -= 1
        self.pieceDropped()

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

    def pieceDropped(self):
        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):
        numFullLines = 0
        rowsToRemove = []
        for i in range(MainBoard.BoardHeight):
            n = 0
            for j in range(MainBoard.BoardWidth):
                if not self.shapeAt(j, i) == ShapeForm.NoShape:
                    n = n + 1
            if n == 10:
                rowsToRemove.append(i)
        rowsToRemove.reverse()
        for m in rowsToRemove:
            for k in range(m, MainBoard.BoardHeight):
                for l in range(MainBoard.BoardWidth):
                    self.setShapeAt(l, k, self.shapeAt(l, k + 1))
        numFullLines = numFullLines + len(rowsToRemove)
        if numFullLines > 0:
            self.numLinesRemoved = self.numLinesRemoved + numFullLines
            self.msg.emit(str(self.numLinesRemoved))
            self.isWaitingAfterLine = True
            self.curPiece.setShape(ShapeForm.NoShape)
            self.update()

    def newPiece(self):
        self.curPiece = Shape()
        self.curPiece.setRandomShape()
        self.curX = MainBoard.BoardWidth // 2 + 1
        self.curY = MainBoard.BoardHeight - 1 + self.curPiece.minY()
        if not self.tryMove(self.curPiece, self.curX, self.curY):
            self.curPiece.setShape(ShapeForm.NoShape)
            self.timer.stop()
            self.isStarted = False
            self.msg.emit("GAME OVER")

    def tryMove(self, newPiece, newX, newY):
        for i in range(4):
            x = newX + newPiece.x(i)
            y = newY - newPiece.y(i)
            if x < 0 or x >= MainBoard.BoardWidth or y < 0 or y >= MainBoard.BoardHeight:
                return False
            if self.shapeAt(x, y) != ShapeForm.NoShape:
                return False
        self.curPiece = newPiece
        self.curX = newX
        self.curY = newY
        self.update()
        return True

    def drawSquare(self, painter, x, y, 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)
class UIUserDefine(QWidget):
    def __init__(self):
        super().__init__()
        self.model = None
        self.playing_index = -1
        self.problem_solving = False

    def init_ui(self):
        self.resize(1200, 680)

        self.timer = QBasicTimer()
        widget1 = QWidget(parent=self)
        widget1.setGeometry(QRect(30, 50, 800, 500))
        table_area = QGroupBox(parent=widget1)  # 图形显示区域
        table_area.setGeometry(
            QRect(widget1.x(), widget1.y(), widget1.width(), widget1.height()))

        self.Plot = DrawUI(width=3, height=3, dpi=100)
        gridlayout1 = QGridLayout(table_area)  # 继承容器groupBox
        gridlayout1.addWidget(self.Plot, 0, 1)

        pic_choose_label = QLabel(self)
        pic_choose_label.move(table_area.x() + table_area.width() + 30,
                              table_area.y() + 20)
        pic_choose_label.setText("Input Maze:")
        pic_choose_label.setFont(QFont("Fixed", 10))
        pic_choose_label2 = QLabel(self)
        pic_choose_label2.move(
            pic_choose_label.geometry().x(),
            pic_choose_label.y() + pic_choose_label.height() + 20)
        pic_choose_label2.setText(
            "(1 is space,0 is wall, 2 is grass, 3 is light)")
        pic_choose_label2.setFont(QFont("Fixed", 10))

        self.maze_input = QPlainTextEdit(parent=self)
        self.maze_input.setGeometry(
            QRect(pic_choose_label2.x(),
                  pic_choose_label2.y() + pic_choose_label2.height() + 20, 250,
                  150))
        self.maze_input.setPlainText(
            '1, 0, 1, 1, 1, 1, 1,\r\n1, 1, 3, 0, 0, 1, 0,\r\n0, 0, 0, 1, 1, 1, 0,\r\n1, 1, 1, 1, 0, 0, 1,\r\n1, 0, 0, 0, 1, 1, 1,\r\n1, 0, 1, 1, 1, 2, 2,\r\n1, 1, 1, 0, 1, 1, 1,'
        )

        period_label = QLabel(parent=self)
        period_label.setText('Light Period:')
        period_label.setFont(QFont("Fixed", 10))
        period_label.move(self.maze_input.x(),
                          self.maze_input.height() + self.maze_input.y() + 10)

        self.period_input = QSpinBox(parent=self)
        self.period_input.setValue(1)
        self.period_input.setFont(QFont("Fixed", 10))
        self.period_input.move(period_label.x() + period_label.width() + 15,
                               period_label.y() - 2)

        period_label2 = QLabel(parent=self)
        period_label2.setText('*2')
        period_label2.setFont(QFont("Fixed", 10))
        period_label2.move(
            self.period_input.x() + self.period_input.width() - 40,
            self.period_input.y() + 2)

        maze_input_button = QPushButton(parent=self)
        maze_input_button.move(
            period_label.x() + period_label.width() + 15,
            self.period_input.y() + self.period_input.height() + 10)
        maze_input_button.setText('Done')
        maze_input_button.setFont(QFont("Fixed", 10))
        maze_input_button.pressed.connect(self.pic_change)

        middle_x = self.maze_input.geometry().x(
        ) + self.maze_input.geometry().width() / 2

        train_epoch_label = QLabel(parent=self)
        train_epoch_label.setText('Training Count:')
        train_epoch_label.setFont(QFont("Fixed", 10))
        train_epoch_label.move(
            self.maze_input.x(),
            maze_input_button.height() + maze_input_button.y() + 40)

        self.epoch_input = QSpinBox(parent=self)
        self.epoch_input.move(
            train_epoch_label.x() + train_epoch_label.width() + 15,
            train_epoch_label.y() - 2)
        self.epoch_input.setValue(30)
        self.epoch_input.setFont(QFont("Fixed", 10))

        train_epoch_label2 = QLabel(parent=self)
        train_epoch_label2.setText('*1000')
        train_epoch_label2.setFont(QFont("Fixed", 10))
        train_epoch_label2.move(
            self.epoch_input.x() + self.epoch_input.width() - 40,
            self.epoch_input.y() + 2)

        self.solve_problem_button = QPushButton(parent=self)
        self.solve_problem_button.setText("Train Now")
        self.solve_problem_button.setFont(QFont("Fixed", 10))
        self.solve_problem_button.move(
            period_label.x() + period_label.width() + 15,
            train_epoch_label.y() + train_epoch_label.height() + 10)
        self.solve_problem_button.pressed.connect(self.solve_button_pressed)

        self.solve_test = QLabel(parent=self)  # 解答过程中的信息显示
        self.solve_test.setText("Training...")
        self.solve_test.setFont(QFont("Fixed", 10))
        self.solve_test.resize(250, self.solve_test.height())
        self.solve_test.move(
            middle_x - self.solve_test.geometry().width() / 2,
            self.solve_problem_button.y() +
            self.solve_problem_button.height() + 10)
        self.solve_test.setHidden(True)

        speed_choose_label = QLabel(self)
        speed_choose_label.move(
            train_epoch_label.x(),
            self.solve_test.y() + self.solve_test.height() + 10)
        speed_choose_label.setText("Play Speed:")
        speed_choose_label.setFont(QFont("Fixed", 10))
        self.play_speed_combo = QComboBox(self)
        self.play_speed_combo.move(
            period_label.x() + period_label.width() + 15,
            speed_choose_label.geometry().y() - 2)
        self.play_speed_combo.addItems(["High", "Middle", "Low"])
        self.play_speed_combo.setFont(QFont("Fixed", 10))

        play_button = QPushButton(self)
        play_button.setText("Play Result Now!")
        play_button.setFont(QFont("Fixed", 10))
        play_button.move(
            period_label.x() + period_label.width() + 15,
            self.play_speed_combo.geometry().y() +
            self.play_speed_combo.geometry().height() + 10)
        play_button.pressed.connect(self.play_button_pressed)

    def pic_change(self):
        self.timer.stop()
        current_text = self.maze_input.toPlainText()
        rows = current_text.split('\n')
        maze_map = []
        try:
            for row in rows:
                row_sp = row.split(',')
                row_list = []
                for c in row_sp:
                    c = c.strip()
                    if len(c) == 0:
                        continue
                    else:
                        row_list.append(int(c))
                maze_map.append(row_list)
        except:
            QMessageBox.information(self, "Warning", "Invalid Input.",
                                    QMessageBox.Ok | QMessageBox.Close,
                                    QMessageBox.Close)
            return

        maze_len = len(maze_map[0])
        for i in range(1, len(maze_map)):
            if len(maze_map[i]) != maze_len:
                QMessageBox.information(
                    self, "Warning",
                    "Error,each row should have the same number of columns.",
                    QMessageBox.Ok | QMessageBox.Close, QMessageBox.Close)
                return

        my_maze = Maze(maze_map=np.array(maze_map),
                       period=self.period_input.value() * 2)
        self.model = QTableModel(my_maze)

        # self.model.play_game((0, 0), 0)
        self.Plot.draw_root(self.model.my_maze, (0, 0), 1, 0, False)
        self.Plot.draw_qtable(qtable_model=self.model,
                              time_=self.model.my_maze.period -
                              1 if self.model.my_maze.period != 0 else 0,
                              fire_flag=True)

    def play_button_pressed(self):
        if self.model == None:
            QMessageBox.information(self, "Tip",
                                    "Please input the maze first.",
                                    QMessageBox.Ok | QMessageBox.Close,
                                    QMessageBox.Close)
            return

        self.model.play_game((0, 0), 0)
        speed_text = self.play_speed_combo.currentText()
        self.playing_index = 0
        if speed_text == "High":
            self.timer.start(100, self)
        elif speed_text == "Middle":
            self.timer.start(500, self)
        else:
            self.timer.start(1500, self)

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            period = self.model.my_maze.period
            if period != 0 and (self.playing_index % period) >= period / 2:
                fire_flag = True
            else:
                fire_flag = False

            self.Plot.draw_qtable(
                self.model, self.playing_index % period if period != 0 else 0,
                fire_flag)
            self.Plot.draw_root(self.model.my_maze, (0, 0), self.playing_index,
                                period, fire_flag)

            self.playing_index = self.playing_index + 1

            if self.playing_index >= len(self.model.my_maze.visited) + 2:
                self.playing_index = 0
                # print("up",self.playing_index)
        else:
            super(UIUserDefine, self).timerEvent(event)

    def solve_button_pressed(self):
        if self.problem_solving:
            return
        if type(self.model) == type(None):
            QMessageBox.information(self, "Tip",
                                    "Please input the maze first.",
                                    QMessageBox.Ok | QMessageBox.Close,
                                    QMessageBox.Close)
            return

        self.problem_solving = True
        self.playing_index = -1
        self.solve_test.setHidden(False)
        self.timer.stop()
        self.repaint()

        train_epoch = self.epoch_input.value() * 1000
        start_time = time.time()
        # path = "tangrams\\" + self.parent().pic_choose_combo.currentText() + ".png"
        self.model.train(output_line=self.solve_test,
                         main_ui=self,
                         epoch_N=train_epoch)
        end_time = time.time()

        QMessageBox.information(
            self, "Tip",
            "Training finished,spend:%.3f s" % (end_time - start_time),
            QMessageBox.Ok | QMessageBox.Close, QMessageBox.Close)

        self.Plot.draw_qtable(qtable_model=self.model,
                              time_=self.model.my_maze.period -
                              1 if self.model.my_maze.period != 0 else 0,
                              fire_flag=True)
        self.problem_solving = False
        self.solve_test.setHidden(True)
class Ui_userDefine(QWidget):
    def __init__(self):
        super().__init__()
        self.model = None
        self.playing_index = -1
        self.problem_solving = False

    def initUI(self):
        self.resize(1200, 700)

        self.timer = QBasicTimer()
        widget1 = QWidget(parent=self)
        widget1.setGeometry(QRect(30, 50, 800, 500))
        table_area = QGroupBox(parent=widget1)  #图形显示区域
        table_area.setGeometry(
            QRect(widget1.x(), widget1.y(), widget1.width(), widget1.height()))

        self.Plot = Draw_ui(width=3, height=3, dpi=100)
        gridlayout1 = QGridLayout(table_area)  # 继承容器groupBox
        gridlayout1.addWidget(self.Plot, 0, 1)

        pic_choose_label = QLabel(self)
        pic_choose_label.move(table_area.x() + table_area.width() + 30,
                              table_area.y() + 20)
        pic_choose_label.setText("输入迷宫:")
        pic_choose_label2 = QLabel(self)
        pic_choose_label2.move(
            pic_choose_label.geometry().x(),
            pic_choose_label.y() + pic_choose_label.height() + 20)
        pic_choose_label2.setText("(1表示空格,0表示墙, 2表示陷阱, 3表示火)")

        self.maze_input = QPlainTextEdit(parent=self)
        self.maze_input.setGeometry(
            QRect(pic_choose_label2.x(),
                  pic_choose_label2.y() + pic_choose_label2.height() + 20, 300,
                  200))
        self.maze_input.setPlainText(
            '1, 0, 1, 1, 1, 1, 1,\r\n1, 1, 3, 0, 0, 1, 0,\r\n0, 0, 0, 1, 1, 1, 0,\r\n1, 1, 1, 1, 0, 0, 1,\r\n1, 0, 0, 0, 1, 1, 1,\r\n1, 0, 1, 1, 1, 2, 2,\r\n1, 1, 1, 0, 1, 1, 1,'
        )

        period_label = QLabel(parent=self)
        period_label.setText('火焰周期:')
        period_label.move(self.maze_input.x(),
                          self.maze_input.height() + self.maze_input.y() + 10)

        self.period_input = QSpinBox(parent=self)
        self.period_input.setValue(1)
        self.period_input.move(period_label.x() + period_label.width() + 15,
                               period_label.y())

        period_label2 = QLabel(parent=self)
        period_label2.setText('*2')
        period_label2.move(
            self.period_input.x() + self.period_input.width() - 40,
            self.period_input.y())

        maze_input_button = QPushButton(parent=self)
        maze_input_button.move(
            self.period_input.x() - 50,
            self.period_input.y() + self.period_input.height() + 10)
        maze_input_button.setText('确认输入')
        maze_input_button.pressed.connect(self.pic_change)

        middle_x = self.maze_input.geometry().x(
        ) + self.maze_input.geometry().width() / 2

        train_epoch_label = QLabel(parent=self)
        train_epoch_label.setText('训练次数上限:')
        train_epoch_label.move(
            self.maze_input.x(),
            maze_input_button.height() + maze_input_button.y() + 40)

        self.epoch_input = QSpinBox(parent=self)
        self.epoch_input.move(
            train_epoch_label.x() + train_epoch_label.width() + 15,
            train_epoch_label.y())
        self.epoch_input.setValue(30)

        train_epoch_label2 = QLabel(parent=self)
        train_epoch_label2.setText('*1000')
        train_epoch_label2.move(
            self.epoch_input.x() + self.epoch_input.width() - 40,
            self.epoch_input.y())

        self.solve_problem_button = QPushButton(parent=self)
        self.solve_problem_button.setText("训练")
        self.solve_problem_button.move(
            maze_input_button.x(),
            train_epoch_label.y() + train_epoch_label.height() + 10)
        self.solve_problem_button.pressed.connect(self.solve_button_pressed)

        self.solve_test = QLabel(parent=self)  # 解答过程中的信息显示
        self.solve_test.setText("正在训练。。。")
        self.solve_test.resize(250, self.solve_test.height())
        self.solve_test.move(
            middle_x - self.solve_test.geometry().width() / 2,
            self.solve_problem_button.y() +
            self.solve_problem_button.height() + 10)
        self.solve_test.setHidden(True)

        speed_choose_label = QLabel(self)
        speed_choose_label.move(
            train_epoch_label.x(),
            self.solve_test.y() + self.solve_test.height() + 10)
        speed_choose_label.setText("播放速度:")
        self.play_speed_combo = QComboBox(self)
        self.play_speed_combo.move(
            speed_choose_label.geometry().x() +
            speed_choose_label.geometry().width() + 30,
            speed_choose_label.geometry().y())
        self.play_speed_combo.addItems(["高速", "中速", "慢速"])

        play_button = QPushButton(self)
        play_button.setText("播放走迷宫过程")
        play_button.move(
            speed_choose_label.x() + 40,
            self.play_speed_combo.geometry().y() +
            self.play_speed_combo.geometry().height() + 10)
        play_button.pressed.connect(self.play_button_pressed)

    def pic_change(self):
        self.timer.stop()
        current_text = self.maze_input.toPlainText()
        rows = current_text.split('\n')
        maze_map = []
        try:
            for row in rows:
                row_sp = row.split(',')
                row_list = []
                for c in row_sp:
                    c = c.strip()
                    if len(c) == 0:
                        continue
                    else:
                        row_list.append(int(c))
                maze_map.append(row_list)
        except:
            QMessageBox.information(self, "提示", "无法解析输入",
                                    QMessageBox.Ok | QMessageBox.Close,
                                    QMessageBox.Close)
            return

        maze_len = len(maze_map[0])
        for i in range(1, len(maze_map)):
            if len(maze_map[i]) != maze_len:
                QMessageBox.information(self, "提示", "错误,每一行的列数应当相等",
                                        QMessageBox.Ok | QMessageBox.Close,
                                        QMessageBox.Close)
                return

        my_maze = Maze(maze_map=np.array(maze_map),
                       period=self.period_input.value() * 2)
        self.model = QTableModel(my_maze)

        #self.model.play_game((0, 0), 0)
        self.Plot.draw_root(self.model.my_maze, (0, 0), 1, 0, False)
        self.Plot.draw_qtable(qtable_model=self.model,
                              time_=self.model.my_maze.period -
                              1 if self.model.my_maze.period != 0 else 0,
                              fire_flag=True)

    def play_button_pressed(self):
        if self.model == None:
            QMessageBox.information(self, "提示", "请先输入迷宫",
                                    QMessageBox.Ok | QMessageBox.Close,
                                    QMessageBox.Close)
            return

        self.model.play_game((0, 0), 0)
        speed_text = self.play_speed_combo.currentText()
        self.playing_index = 0
        if speed_text == "高速":
            self.timer.start(150, self)
        elif speed_text == "中速":
            self.timer.start(500, self)
        else:
            self.timer.start(1500, self)

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            period = self.model.my_maze.period
            if period != 0 and (self.playing_index % period) >= period / 2:
                fire_flag = True
            else:
                fire_flag = False

            self.Plot.draw_qtable(
                self.model, self.playing_index % period if period != 0 else 0,
                fire_flag)
            self.Plot.draw_root(self.model.my_maze, (0, 0), self.playing_index,
                                period, fire_flag)

            self.playing_index = self.playing_index + 1

            if self.playing_index >= len(self.model.my_maze.visited) + 2:
                self.playing_index = 0
                # print("up",self.playing_index)
        else:
            super(Ui_userDefine, self).timerEvent(event)

    def solve_button_pressed(self):
        if self.problem_solving:
            return
        if type(self.model) == type(None):
            QMessageBox.information(self, "提示", "请先输入迷宫",
                                    QMessageBox.Ok | QMessageBox.Close,
                                    QMessageBox.Close)
            return

        self.problem_solving = True
        self.playing_index = -1
        self.solve_test.setHidden(False)
        self.timer.stop()
        self.repaint()

        train_epoch = self.epoch_input.value() * 1000
        start_time = time.time()
        #path = "tangrams\\" + self.parent().pic_choose_combo.currentText() + ".png"
        self.model.train(output_line=self.solve_test,
                         main_ui=self,
                         epoch_N=train_epoch)
        end_time = time.time()

        QMessageBox.information(self, "提示",
                                "完成训练,用时:%.3f s" % (end_time - start_time),
                                QMessageBox.Ok | QMessageBox.Close,
                                QMessageBox.Close)

        self.Plot.draw_qtable(qtable_model=self.model,
                              time_=self.model.my_maze.period -
                              1 if self.model.my_maze.period != 0 else 0,
                              fire_flag=True)
        self.problem_solving = False
        self.solve_test.setHidden(True)
예제 #27
0
class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        # checkBox
        cb = QCheckBox('show title', self)
        cb.move(10, 10)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)

        # 颜色混合
        self.col = QColor(0, 0, 0)
        redb = QPushButton('Red', self)
        redb.setCheckable(True)
        redb.move(10, 30)
        redb.clicked[bool].connect(self.setColor)

        grnb = QPushButton('Green', self)
        grnb.setCheckable(True)
        grnb.move(10, 60)
        grnb.clicked[bool].connect(self.setColor)

        blueb = QPushButton('Blue', self)
        blueb.setCheckable(True)
        blueb.move(10, 90)
        blueb.clicked[bool].connect(self.setColor)

        self.square = QFrame(self)
        self.square.setGeometry(150, 20, 50, 50)
        self.square.setStyleSheet("QWidget { background-color: %s}" %
                                  self.col.name())

        # slider 滚动条
        sld = QSlider(Qt.Horizontal, self)
        sld.setFocusPolicy(Qt.NoFocus)
        sld.setGeometry(10, 120, 100, 10)
        sld.valueChanged[int].connect(self.changeValue)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('1.png'))
        self.label.setGeometry(150, 90, 80, 80)

        # 进度条ProgressBar
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(10, 170, 200, 20)
        self.btn = QPushButton('Start', self)
        self.btn.move(10, 200)
        self.btn.clicked.connect(self.doAction)

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

        # Calendar 日历
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.move(10, 230)
        cal.clicked[QDate].connect(self.showDate)
        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(80, 440)

        self.setGeometry(300, 200, 300, 500)
        self.setWindowTitle('Toggle')
        self.show()

    def changeTitle(self, state):
        if state == Qt.Checked:
            self.setWindowTitle('Toogle')
        else:
            self.setWindowTitle(' ')

    def setColor(self, pressed):
        source = self.sender()
        if pressed:
            val = 255
        else:
            val = 0

        if source.text() == "Red":
            self.col.setRed(val)
        elif source.text() == "Green":
            self.col.setGreen(val)
        else:
            self.col.setBlue(val)

        self.square.setStyleSheet("QFrame {background-color: %s}" % self.col.name())

    def changeValue(self, value):
        if value == 0:
            self.label.setPixmap(QPixmap('1.png'))
        elif 0 < value <= 30:
            self.label.setPixmap(QPixmap('2.png'))
        elif 30 < value < 80:
            self.label.setPixmap(QPixmap('3.png'))
        else:
            self.label.setPixmap(QPixmap('4.png'))

    def timerEvent(self, *args, **kwargs):
        if self.step >= 100:
            self.timer.stop()
            self.btn.setText('Finished')
            return
        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.btn.setText('Stop')

    def showDate(self, date):
        self.lbl.setText(date.toString())
예제 #28
0
class SpielFeld(QWidget):

    #Array construction
    PlayFieldAR = [[0 for x in range(100)] for y in range(100)]
    BarrierList = []

    # Teleport Positions
    TP_TopL = QVector2D(100, 100)
    TP_TopR = QVector2D(850, 100)
    TP_BotL = QVector2D(100, 850)
    TP_BotR = QVector2D(850, 850)


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

        self.initUI()

    def initUI(self):

        self.setGeometry(0, 0, SCREENWIDTH, SCREENHEIGHT)
        self.setWindowTitle('Game.exe')
        self.center()
        self.timer = QBasicTimer()
        self.timer.start(FPS, self)
        self.tickCount = 0

        #set Walls, set array value to 1 to place Wall

        #set Wall around the edges
        for x in range(0,100,1):
            SpielFeld.PlayFieldAR[x][0]= 1
            SpielFeld.PlayFieldAR[x][99]= 1
        for y in range(1,99,1):
            SpielFeld.PlayFieldAR[0][y]= 1
            SpielFeld.PlayFieldAR[99][y]= 1

        #set some Obstacle
        #for i in range(0, 25, 1):
        #    SpielFeld.PlayFieldAR[10][i+10] = 1
        #    SpielFeld.PlayFieldAR[90][i+10] = 1
        #    SpielFeld.PlayFieldAR[10][i+65] = 1
        #    SpielFeld.PlayFieldAR[90][i+65] = 1

        #for i in range(0, 25, 1):
        #    SpielFeld.PlayFieldAR[i+10][10] = 1
        #    SpielFeld.PlayFieldAR[i+10][90] = 1
        #    SpielFeld.PlayFieldAR[90-i][10] = 1
        #    SpielFeld.PlayFieldAR[90-i][90] = 1

        #for i in range(0, 31, 1):
        #    SpielFeld.PlayFieldAR[i+35][30] = 1
        #    SpielFeld.PlayFieldAR[i+35][70] = 1
        #    SpielFeld.PlayFieldAR[30][i+35] = 1
        #    SpielFeld.PlayFieldAR[70][i + 35] = 1


        #set some Obstacle
        for i in range(0, 25, 1):
            SpielFeld.PlayFieldAR[70][i+45] = 1
        for i in range(0, 40, 1):
            SpielFeld.PlayFieldAR[i+10][40] = 1
        for i in range(0, 50, 1):
            SpielFeld.PlayFieldAR[i+30][70] = 1
        for i in range(0, 30, 1):
            SpielFeld.PlayFieldAR[i+25][20] = 1
        for i in range(0, 10, 1):
            SpielFeld.PlayFieldAR[10][i+50] = 1

            
        for i in range(0, 100, 1):
            for j in range(0, 100, 1):
                if SpielFeld.PlayFieldAR[i][j]==1:
                    SpielFeld.BarrierList.append(QVector2D(i,j))
        
        #init Robots
        Robot1 = RoboTypeRun(1, QVector2D(500,500), 0, 2, 2, 20, 40 ,PINK)
        Robot2 = RoboTypeChase1(2, QVector2D(200,200), 90, 2, 2, 20, 50,DARKBLUE)
        Robot3 = RoboTypeChase2(3, QVector2D(550,550), 180, 2, 2, 30, 60,LIGHTBLUE)
        Robot4 = RoboTypeChase3(4, QVector2D(600,150), 270, 2, 2, 25, 85,ORANGE)

        self.robots = [Robot1, Robot2, Robot3, Robot4]

        for robot in self.robots:
            robot.start()

        self.show()

    def center(self):
        '''centers the window on the screen'''

        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)

    def timerEvent(self, Event):
        #Count
        self.tickCount += 1
        
        #update RobotLists of each Robot
        if self.tickCount % 10 == 0:
            for y in self.robots:
                for x in self.robots:
                    y.RobotList[x.robotid] = x.position

        # move robots on the game field
        for robot in self.robots:
            self.moveRobot(robot)
            self.barrierCollision(robot)
            self.collision(robot, self.robots[0])

        self.update()              

    def paintEvent(self, qp):

        qp = QPainter()
        qp.begin(self)
        self.drawField(qp)
        # draw Robots on the game field
        for robot in self.robots:
            self.drawRobo(robot,qp)


    def drawRobo(self, Robo, br):
        br.setBrush(Robo.color)
        br.setPen(QColor(0,0,0))
        br.drawEllipse(int(round(Robo.position.x())), int(round(Robo.position.y())) , 2* Robo.radius, 2*Robo.radius)

        # Berechnung der neuen xPos und yPos für die Blickausrichtung
        xPos = math.cos(math.radians(Robo.alpha)) * Robo.radius
        yPos = math.sin(math.radians(Robo.alpha)) * Robo.radius

        br.drawLine(int(round(Robo.position.x())) + Robo.radius, int(round(Robo.position.y())) + Robo.radius,
                    (int(round(Robo.position.x())) + Robo.radius) + xPos, (int(round(Robo.position.y())) + Robo.radius) - yPos)

        #draw FOV
        if VISUALS:
            br.setPen(QColor(255,255,255))
            xPos = math.cos(math.radians(Robo.alpha + (Robo.FOV/2))) * Robo.radius
            yPos = math.sin(math.radians(Robo.alpha + (Robo.FOV/2))) * Robo.radius
            br.drawLine(int(round(Robo.position.x())) + Robo.radius, int(round(Robo.position.y())) + Robo.radius,
                        (int(round(Robo.position.x())) + Robo.radius) + 10*xPos, (int(round(Robo.position.y())) + Robo.radius) - 10*yPos)
            xPos = math.cos(math.radians(Robo.alpha - (Robo.FOV/2))) * Robo.radius
            yPos = math.sin(math.radians(Robo.alpha - (Robo.FOV/2))) * Robo.radius
            br.drawLine(int(round(Robo.position.x())) + Robo.radius, int(round(Robo.position.y())) + Robo.radius,
                        (int(round(Robo.position.x())) + Robo.radius) + 10*xPos, (int(round(Robo.position.y())) + Robo.radius) - 10*yPos)
 

    def drawField(self, qp):
        #Draw the PlayField
        for i in range(0, 100, 1):
            for j in range(0, 100, 1):
                if SpielFeld.PlayFieldAR[i][j]==1:
                    qp.setBrush(QColor(65, 50, 25))
                    qp.drawRect(i*10, j*10, 10, 10)
                else:
                    qp.setBrush(QColor(50, 155, 50))
                    qp.drawRect(i*10, j*10, 10, 10)

    def moveRobot(self, Robo):
        #berechne neue Lenkrichtung
        if (abs(Robo.v_alpha) <= alpha_eps) and (abs(Robo.a_alpha) <= alpha_eps):
            Robo.v_alpha = 0
        elif (Robo.v_alpha + Robo.a_alpha) < -v_alpha_Max:
            Robo.v_alpha = -v_alpha_Max
        elif (Robo.v_alpha + Robo.a_alpha) <= v_alpha_Max:
            Robo.v_alpha = (Robo.v_alpha + Robo.a_alpha)
        elif (Robo.v_alpha + Robo.a_alpha) >= v_alpha_Max:
            Robo.v_alpha = v_alpha_Max

        #Neue Richtung
        Robo.alpha = (Robo.alpha + Robo.v_alpha) % 360
        
        #berechne geschwindigkeit
        v= math.sqrt(math.pow(Robo.v_vector.x(),2) + math.pow(Robo.v_vector.y(),2))
        
        if (v + Robo.a) <= 0:
            v = 0
            Robo.a = 0
        elif (v + Robo.a) < vMax:
            v += Robo.a
        elif (v + Robo.a) >= vMax:
            v = vMax

        #X-Y Geschwindigkeit
        GesX = math.cos(math.radians(Robo.alpha)) * v
        GesY = - math.sin(math.radians(Robo.alpha)) * v

        #setze neue Geschwindigkeit
        Robo.v_vector = QVector2D(GesX,GesY)

        #berechne neue Position
        Robo.position.__iadd__(Robo.v_vector)



    def barrierCollision(self, robo):
        #Collision with Obstacles
        PosX = int(round(robo.position.x()/ 10))
        PosY = int(round(robo.position.y()/ 10))
        Rad = int(round((robo.radius *2)/10))
        for i in range(0, Rad, 1):
            #oben
            if (SpielFeld.PlayFieldAR[PosX + i][PosY-1] == 1) & (robo.v_vector.y()<0):
                robo.position.__isub__(robo.v_vector)
                robo.v_vector = QVector2D(0,0)
                robo.a = 0
            #unten
            if (SpielFeld.PlayFieldAR[PosX + i][PosY + Rad] == 1) & (robo.v_vector.y()>0):
                robo.position.__isub__(robo.v_vector)
                robo.v_vector = QVector2D(0,0)
                robo.a = 0
            #links
            if (SpielFeld.PlayFieldAR[PosX - 1][PosY + i] == 1) & (robo.v_vector.x()<0):
                robo.position.__isub__(robo.v_vector)
                robo.v_vector = QVector2D(0,0)
                robo.a = 0
            #rechts
            if (SpielFeld.PlayFieldAR[PosX + Rad][PosY + i] == 1) & (robo.v_vector.x()>0):
                robo.position.__isub__(robo.v_vector)
                robo.v_vector = QVector2D(0,0)
                robo.a = 0


    def distanceTwoPoints(self, x1, y1, x2, y2):
        return math.sqrt((x2-x1) * (x2-x1) + (y2-y1)*(y2-y1))

    def distance(self, robo1, robo2):
        return self.distanceTwoPoints(int(round(robo1.position.x())) + robo1.radius,
                                                  int(round(robo1.position.y()))+ robo1.radius,
                                                  int(round(robo2.position.x())) + robo2.radius,
                                                  int(round(robo2.position.y())) + robo2.radius)


    def collision(self, robo, target):
        for robot in self.robots:
            if robot != robo and robot != target and robo != target :
                distance = self.distance(robot, robo)

                if distance <= robot.radius + robo.radius :

                    # with elastic collision, does not apply to the reality because of spin, friction etc.
                    # our only concern is the mass of the robots
                    # new velocity of robo1
                    newVelX1 = (int(round(robo.v_vector.x())) * (robo.mass - robot.mass) + (2 * robot.mass * int(round(robot.v_vector.x())))) / (
                            robo.mass + robot.mass)
                    newVelY1 = (int(round(robo.v_vector.y()))* (robo.mass - robot.mass) + (2 * robot.mass * int(round(robot.v_vector.y())))) / (
                            robo.mass + robot.mass)

                    # new velocity of robo2
                    newVelX2 = (int(round(robot.v_vector.x())) * (robot.mass - robo.mass) + (2 * robo.mass * int(round(robo.v_vector.x())))) / (
                            robo.mass + robot.mass)
                    newVelY2 = (int(round(robot.v_vector.y())) * (robot.mass - robo.mass) + (2 * robo.mass * int(round(robo.v_vector.y())))) / (
                            robo.mass + robot.mass)

                    newV_1 = QVector2D(newVelX1, newVelY1)
                    newV_2 = QVector2D(newVelX2, newVelY2)

                    robo.position.__iadd__(newV_1)

                    robot.position.__iadd__(newV_2)

            else: self.teleport(target, robo)



    def teleport(self, target, robot):

        MID = 500

        if robot != target:
            distance = self.distance(robot, target)

            if distance <= target.radius + robot.radius:

                if  int(round(target.position.x())) > MID and  int(round(target.position.y())) < MID:

                    robot.position = QVector2D(100,850)

                elif int(round(target.position.x())) > MID and int(round(target.position.y())) > MID:
                    robot.position = QVector2D(100,100)

                elif int(round(target.position.x())) < MID and int(round(target.position.y())) < MID:
                    robot.position = QVector2D(850,850)


                elif int(round(target.position.x())) < MID and int(round(target.position.y())) > MID:
                    robot.position = QVector2D(850,100)

                robot.v_vector = QVector2D(0,0)
                robot.a =0
                robot.a_alpha =0
                robot.v_alpha = 0
예제 #29
0
class Board(QFrame):
    """
    Main board drawing ambulatory room + animation
    """

    emitText = pyqtSignal(str)

    refreshRate = 300
    board_width = 720
    board_height = 560
    graph_width = int(board_width / 80)
    graph_height = int(board_height / 80)
    tile_size = 80
    player_size = 80
    move_speed = 20
    debug_mode = False
    right_foot = False

    player_x = 0
    player_y = 160
    is_operating = False

    inference_method = "Regułowe"
    pathFinding = "aStar"

    def __init__(self, parent):

        super().__init__(parent)
        self.parent = parent
        # self.initBoard()

        self.loadPixmaps()
        self.use_this_pixmap = self.nurse_pixmap

        # setting logical value for information about animation state
        self.isStopped = False
        self.isActive = False

        self.symptoms = []

        # creating empty list of points of size board_width x board_height
        self.board = [
            [
                ''
                for x in range(self.board_width)
            ]
            for y in range(self.board_height)
        ]

        # creating list of static map objects
        # PIXMAPs are declared in function self.loadPixmaps()

        self.objects = {
            Object("curtain1",  (0, 0),     (80, 160),  7),
            Object("bed1",      (80, 0),    (80, 160),  4),
            Object("curtain2",  (240, 0),   (80, 160),  7),
            Object("bed2",      (320, 0),   (80, 160),  4),
            Object("curtain3",  (480, 0),   (80, 160),  7),
            Object("bed3",      (560, 0),   (80, 160),  5),
            # Object("table_top", (640, 240), (80, 80),   8, 90),
            Object("table",     (640, 400), (80, 80),   9, 90),
            Object("curtain4",  (0, 240),   (160, 80),  7, 90),
            Object("bed4",      (0, 320),   (160, 80),  6, 270),
            Object("curtain5",  (0, 480),   (160, 80),  7, 90),
            # Object
        }

        for obj in self.objects:
            if obj.getName() == 'bed3' or obj.getName() == 'bed4':
                obj.changePixmap(4)

        """
        Creating graph to get paths
        """
        self.graph = GridWithWeights(self.graph_width,
                                     self.graph_height)
        self.graph.setWalls(*self.objects)
        self.path = []

        # drawing static objects on map
        # self.fillBoard(80, 0, 40, 80, 'bed')

        # creating timer
        self.timer = QBasicTimer()

    def diagnose(self):
        self.is_operating = True
        get_symptoms_disease_relation_from_rows()
        if self.inference_method == 'Regułowe':
            diseases_list = []
            symptom_list = []
            name = str(randint(0, 1000000))
            while (True):
                self.emitText.emit("Nurse: Co Ci dolega?")

                while not self.symptoms:
                    time.sleep(0.1)
                if (self.symptoms): symptom_list.append(self.symptoms)

                symp = check_knowledge(dict, self.symptoms)
                print(dict)
                if (check_knowledge(dict, self.symptoms)):
                    result = check_knowledge(dict, self.symptoms)
                    self.emitText.emit("masz %s ?" % result[0])
                    self.emitText.emit("Jeśli tak to cierpisz na %s" % result[1])
                    break
                diseases_list = Diagnosis.perform_diagnosis(name, self.symptoms)
                if (len(diseases_list) == 1):
                    break
                else:
                    self.emitText.emit("--Liczba możliwych chorób to: %s--" % len(diseases_list))
                self.symptoms = []

            if (diseases_list):
                self.emitText.emit("%s cierpi na: %s" % (name, diseases_list[0]))
                key = str(diseases_list[0])
                dict.setdefault(key, [])
                dict.update({key: symptom_list})

            self.getPatientOufOf(self.current_bed)
            self.is_operating = False
            self.symptoms = []

    @pyqtSlot(str)
    def inferenceEmitted(self, method):
        self.inference_method = method

    @pyqtSlot(str)
    def pathMethod(self, method):
        if method == "A Star":
            self.pathFinding = "aStar"
        elif method == "Dijkstra":
            self.pathFinding = "dijkstra"

    @pyqtSlot()
    def newPatient(self):
        emptyBeds = self.getEmptyBeds()

        if emptyBeds:
            index = randint(0, len(emptyBeds) - 1)
            self.putPatientInto(emptyBeds[index].getName())
        else:
            self.emitText.emit('Brak wolnych lóżek')

    @pyqtSlot(str)
    def textEmitted(self, symptoms):

        self.symptoms = SymptomLoader.scanInput(symptoms)

    def loadPixmaps(self):
        base_dir = os.path.dirname(os.path.abspath(__file__))
        base_dir = base_dir[:-4]

        # tiles = QImage(base_dir + r'/images/40_kafelki.gif')
        # tiles = QImage(base_dir + r'/images/podloga80x80.png')
        # tiles = QImage(base_dir + r'/images/podloga1_80x80.png')
        # tiles = QImage(base_dir + r'/images/podloga2_80x80.png')
        # tiles = QImage(base_dir + r'/images/podloga3_80x80.png')
        tiles = QImage(base_dir + r'/images/podloga4_80x80.png')
        # tiles = QImage(base_dir + r'/images/kafelki.gif')
        self.tiles_brush = QBrush(tiles)

        """
        self.nurse_pixmap = QPixmap(base_dir +
                                    r'/images/nurse_standing40x40.png')
        """

        self.nurse_pixmap = QPixmap(base_dir +
                                    r'/images/nurse_standing80x80.png')
        self.nurse_pixmap_base = self.nurse_pixmap

        """
        self.nurse_left_pixmap = QPixmap(base_dir +
                                         r'/images/nurse_left40x40.png')
        """
        self.nurse_left_pixmap = QPixmap(base_dir +
                                         r'/images/nurse_left80x80.png')
        self.nurse_left_pixmap_base = self.nurse_left_pixmap

        """
        self.nurse_right_pixmap = QPixmap(base_dir +
                                            r'/images/nurse_right40x40.png')
        """
        self.nurse_right_pixmap = QPixmap(base_dir +
                                          r'/images/nurse_right80x80.png')

        # self.nurse_pixmap = QPixmap(base_dir +
        # r'/images/nurse_standing40x40.png')
        # self.nurse_pixmap = QPixmap(base_dir +
        # r'/images/nurse_standing80x80.png')
        self.nurse_pixmap = QPixmap(base_dir +
        r'/images/pigula_koczek80x80.png')
        self.nurse_pixmap_base = self.nurse_pixmap

        # self.nurse_left_pixmap = QPixmap(base_dir +
        # r'/images/nurse_left40x40.png')
        # self.nurse_left_pixmap = QPixmap(base_dir +
        # r'/images/nurse_left80x80.png')
        self.nurse_left_pixmap = QPixmap(base_dir +
        r'/images/pigula_koczek_lewa80x80.png')
        self.nurse_left_pixmap_base = self.nurse_left_pixmap

        # self.nurse_right_pixmap = QPixmap(base_dir +
        # r'/images/nurse_right40x40.png')
        # self.nurse_right_pixmap = QPixmap(base_dir +
        # r'/images/nurse_right80x80.png')
        self.nurse_right_pixmap = QPixmap(base_dir +
        r'/images/pigula_koczek_prawa80x80.png')

        self.nurse_right_pixmap_base = self.nurse_right_pixmap

        """
        self.empty_bed_pixmap = QPixmap(base_dir +
                                        r'/images/lozko40x80.gif')
        """

        self.empty_bed_pixmap = QPixmap(base_dir +
                                        r'/images/lozko80x160.gif')

        """
        self.girl_alarm_pixmap = QPixmap(base_dir +
                                           r'/images/girlAlarm40x80.gif')
        """

        self.girl_alarm_pixmap = QPixmap(base_dir +
                                         r'/images/girlAlarm80x160.gif')

        # self.empty_bed_pixmap = QPixmap(base_dir +
        # r'/images/lozko40x80.gif')
        # self.empty_bed_pixmap = QPixmap(base_dir +
        # r'/images/lozko80x160.gif')
        self.empty_bed_pixmap = QPixmap(base_dir +
        r'/images/lozko7_80x160.png')

        """
        self.girl_sleeping_pixmap = QPixmap(base_dir +
                                            r'/images/girlSleeping40x80.gif')
        """

        self.girl_sleeping_pixmap = QPixmap(base_dir +
                                            r'/images/girlSleeping80x160.gif')
        # self.girl_sleeping_pixmap = QPixmap(base_dir +
        # r'/images/girlSleeping40x80.gif')
        # self.girl_sleeping_pixmap = QPixmap(base_dir +
        # r'/images/girlSleeping80x160.gif')
        self.girl_sleeping_pixmap = QPixmap(base_dir +
        r'/images/lozko7_asleep_80x160.png')

        # self.table_top_pixmap = QPixmap(base_dir + r'/images/blat40x40.png')
        self.table_top_pixmap = QPixmap(base_dir + r'/images/blat80x80.png')

        # self.table_pixmap = QPixmap(base_dir + r'/images/szafka40x40.png')
        self.table_pixmap = QPixmap(base_dir + r'/images/szafka80x80.png')

        """
        self.curtain_pixmap = QPixmap(base_dir +
                                      r'/images/CurtainOnly40x80.gif')
        self.curtain_pixmap = QPixmap(base_dir +
                                      r'/images/CurtainOnly40x160.gif')
        """

        self.curtain_pixmap = QPixmap(base_dir +
                                      r'/images/CurtainOnly80x160.gif')

        # creating dictionary of brushes!
        self.pixmaps = {
            1: self.nurse_pixmap,
            2: self.nurse_left_pixmap,
            3: self.nurse_right_pixmap,
            4: self.empty_bed_pixmap,
            5: self.girl_alarm_pixmap,
            6: self.girl_sleeping_pixmap,
            7: self.curtain_pixmap,
            8: self.table_top_pixmap,
            9: self.table_pixmap
        }

    @pyqtSlot()
    def start(self):
        """
        Function responsible for preparing animation when
        start button has been pressed
        """

        if self.isActive:
            return

        if self.isStopped:
            self.isStopped = False

        self.isActive = True

        self.timer.start(self.refreshRate, self)

    @pyqtSlot()
    def stop(self):
        """
        Function responsible for stoping animation when
        stop button pressed
        """
        if not self.isActive:
            return

        self.isStopped = True
        self.isActive = False

        self.timer.stop()

        self.update()

    @pyqtSlot(str)
    def move(self, direction):
        """
        Function responsible for moving main character up.
        """

        self.rotatePlayer(direction)
        self.fillRealBoard(self.player_x, self.player_y,
                           self.player_size, self.player_size, '')

        if direction == 'up' and not self.collision(direction):
            self.makeStep(direction, -self.move_speed)

        elif direction == 'right' and not self.collision(direction):
            self.makeStep(direction, self.move_speed)

        elif direction == 'down' and not self.collision(direction):
            self.makeStep(direction, self.move_speed)

        elif direction == 'left' and not self.collision(direction):
            self.makeStep(direction, -self.move_speed)

        self.fillRealBoard(self.player_x, self.player_y,
                           self.player_size, self.player_size, 'player')

    def makeStep(self, direction, distance):
        # print('distance: ' + str(distance) + '\t 1/4th: ' + str(distance/4))

        # determining size of first step (can't be float)
        half_of_distance = int(distance / 2)

        # determinig which foot now
        if self.right_foot:
            foot_pixmap = self.nurse_left_pixmap
        else:
            foot_pixmap = self.nurse_right_pixmap

        # next time it will be another foot
        self.right_foot = not self.right_foot

        if direction in ['up', 'down']:
            # changing POS_Y
            self.player_y += half_of_distance
            self.use_this_pixmap = foot_pixmap
            self.repaint()

            time.sleep(0.05)

            self.player_y += half_of_distance
            self.use_this_pixmap = self.nurse_pixmap
            self.repaint()

        elif direction in ['left', 'right']:
            # changing POS_X
            self.player_x += half_of_distance
            self.use_this_pixmap = foot_pixmap
            self.repaint()

            time.sleep(0.05)

            self.player_x += half_of_distance
            self.use_this_pixmap = self.nurse_pixmap
            self.repaint()

    @pyqtSlot()
    def debug(self):
        """
        PyQt slot for signal to change map-drawing-mode
        debug   - black background & red objects
        normal  - normal :P
        """

        self.debug_mode = not self.debug_mode

    def getEmptyBeds(self):
        emptyBeds = []

        for obj in self.objects:
            if ((obj.getName() == 'bed1' or
                    obj.getName() == 'bed2' or
                    obj.getName() == 'bed3' or
                    obj.getName() == 'bed4') and
                    (obj.getPixmap() is 4)):
                emptyBeds.append(obj)

        return emptyBeds

    def getTakenBeds(self):
        takenBeds = []

        for obj in self.objects:
            if ((obj.getName() == 'bed1' or
                    obj.getName() == 'bed2' or
                    obj.getName() == 'bed3' or
                    obj.getName() == 'bed4') and
                    (obj.getPixmap() is not 4)):
                takenBeds.append(obj)

        return takenBeds

    def putSleepingPatientInto(self, bed_name):
        for obj in self.objects:
            if obj.getName() == bed_name and obj.getPixmap() != 6:
                obj.changePixmap(6)

    def putPatientInto(self, bed_name):
        for obj in self.objects:
            if obj.getName() == bed_name and obj.getPixmap() != 5:
                obj.changePixmap(5)

    def getPatientOufOf(self, bed_name):
        for obj in self.objects:
            if obj.getName() == bed_name and obj.getPixmap() != 4:
                obj.changePixmap(4)

    def rotatePlayer(self, direction):
        """
        Function responsible for rotating players icon.
        """

        rotation = QTransform()

        if direction == 'up':
            rotation.rotate(0)
        elif direction == 'right':
            rotation.rotate(90)
        elif direction == 'down':
            rotation.rotate(180)
        elif direction == 'left':
            rotation.rotate(270)

        self.use_this_pixmap = \
            self.nurse_pixmap_base.transformed(rotation)
        self.nurse_pixmap = \
            self.nurse_pixmap_base.transformed(rotation)
        self.nurse_left_pixmap = \
            self.nurse_left_pixmap_base.transformed(rotation)
        self.nurse_right_pixmap = \
            self.nurse_right_pixmap_base.transformed(rotation)

        """
        self.player_left_brush =
        QBrush(self.player_left_base.transformed(rotation))
        self.player_right_brush =
        QBrush(self.player_right_base.transformed(rotation))
        self.player_brush =
        QBrush(self.player_image_base.transformed(rotation))
        """

    def collision(self, direction):
        """
        Main function responsible for collision detection.
        """

        # These -/+ 1 comes from the fact, that we aren't checking
        # corners but pixels diagonally to the inside of player icon
        # @@@@@@@@@@@@
        # @*@@@@@@@@*@
        # @@@@@@@@@@@@
        # @@@@@@@@@@@@
        # @@@@@@@@@@@@
        # @*@@@@@@@@*@
        # @@@@@@@@@@@@

        # (x1, y1) - TOP LEFT
        # (x2, y2) - TOP RIGHT
        if direction == 'up':
            x1 = self.player_x + 1
            y1 = self.player_y - self.move_speed + 1

            x2 = self.player_x + self.player_size - 1
            y2 = y1

        # (x1, y1) - TOP RIGHT
        # (x2, y2) - BOTTOM RIGHT
        elif direction == 'right':
            x1 = self.player_x + self.player_size + self.move_speed - 1
            y1 = self.player_y + 1

            x2 = x1
            y2 = self.player_y + self.player_size - 1

        # (x1, y1) - BOTTOM LEFT
        # (x2, y2) - BOTTOM RIGHT
        elif direction == 'down':
            x1 = self.player_x + 1
            y1 = self.player_y + self.player_size + self.move_speed - 1

            x2 = self.player_x + self.player_size - 1
            y2 = y1

        # (x1, y1) - TOP LEFT
        # (x2, y2) - BOTTOM LEFT
        elif direction == 'left':
            x1 = self.player_x - self.move_speed + 1
            y1 = self.player_y + 1

            x2 = x1
            y2 = self.player_y + self.player_size - 1

        try:
            # no collision if value is "" (empty string)
            if self.board[y1][x1] or self.board[y2][x2]:
                print("Collision! There is: {0} or \
                      {1}".format(self.board[y1][x1], self.board[y2][x2]))
                return True
            elif direction == 'up' and y1 < 0:
                return True
            elif direction == 'right' and x1 > self.board_width:
                return True
            elif direction == 'down' and y1 > self.board_height:
                return True
            elif direction == 'left' and x1 < 0:
                return True
            else:
                return False
        except IndexError:
            return True

    def paintEvent(self, event):

        painter = QPainter(self)

        if self.debug_mode:
            self.drawRealBoard(painter)
        else:
            self.drawBoard(painter)
            self.drawPlayer(painter)

        self.update()

    def timerEvent(self, event):
        """
        Overwritten function of timer event
        """

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

            if not self.is_operating and takenBeds:
                self.goToPatient(takenBeds)

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

    def goToPatient(self, takenBeds):
        if takenBeds:
            index = randint(0, len(takenBeds) - 1)
            x, y = takenBeds[index].getPosition()
            sizeX, sizeY = takenBeds[index].getSize()

            pointX = int(x / 80)
            pointY = int(y / 80)

            if takenBeds[index].getName() == 'bed4':
                pointY = int(pointY + sizeY / 80)
            else:
                pointX = int(pointX + sizeX / 80)

            self.current_bed = takenBeds[index].getName()

            playerX = int(self.player_x / 80)
            playerY = int(self.player_y / 80)

            if self.pathFinding == "aStar":
                cameFrom, costSoFar = self.aStarSearch(self.graph,
                                                      (playerX, playerY),
                                                      (pointX, pointY))
            elif self.pathFinding == "dijkstra":
                cameFrom, costSoFar = self.dijkstraSearch(self.graph,
                                                         (playerX, playerY),
                                                         (pointX, pointY))

            self.path = self.reconstructPath(cameFrom,
            (playerX, playerY),
            (pointX, pointY))

            if playerX is pointX and playerY is pointY:
                self.is_operating = True
                diagnoseThread = threading.Thread(target=self.diagnose)
                diagnoseThread.start()
            else:
                self.movePlayer()

    def movePlayer(self):
        pathToMove = self.path[1:]

        for nextPointX, nextPointY in pathToMove:
            nextPointX = nextPointX * 80
            nextPointY = nextPointY * 80

            if self.player_x < nextPointX:
                while self.player_x < nextPointX:
                    self.move('right')
            elif self.player_x > nextPointX:
                while self.player_x > nextPointX:
                    self.move('left')
            elif self.player_y < nextPointY:
                while self.player_y < nextPointY:
                    self.move('down')
            elif self.player_y > nextPointY:
                while self.player_y > nextPointY:
                    self.move('up')


    def drawBoard(self, painter):
        """
        Main function for QPainter
        """

        # drawing tiles
        painter.setBrush(self.tiles_brush)
        painter.drawRect(
            0,
            0,
            self.board_width,
            self.board_height
        )

        self.drawObjects(painter)

    def drawObjects(self, painter):
        """
        Drawing objects like bed or curtain on map.
        """

        # reminder:
        # obj = [(pos_x, pos_y), (width, height), PIXMAP, ROTATION_ANGLE]
        for obj in self.objects:
            if obj.getAngle() != 0:
                rotation = QTransform()
                rotation.rotate(obj.getAngle())
                pixmap = self.pixmaps[obj.getPixmap()].transformed(rotation)
            else:
                pixmap = self.pixmaps[obj.getPixmap()]

            state = obj.getState()
            painter.drawPixmap(
                state[0],   # pos_x
                state[1],   # pos_y
                state[2],   # width
                state[3],   # height
                pixmap
            )

            # Drawing path - delete when not needed
            for (x, y) in self.path:
                painter.setPen(Qt.red)
                painter.drawRect(x * 80, y * 80, 80, 80)

            self.fillRealBoard(
                state[0],   # pos_x
                state[1],   # pos_y
                state[2],   # width
                state[3],   # height
                obj.getName()
            )

    def fillRealBoard(self, start_x, start_y, width, height, content):
        for y in range(start_y, start_y + height):
            for x in range(start_x, start_x + width):
                self.board[y][x] = content

        """
        print('filling board from {0} to {1} and \
              from {2} to {3} with {4}'.format(start_x, width,
                                               start_y, height, content))
        """

    def drawRealBoard(self, painter):
        """
        Only for debug, prints self.board pixel by pixel
        """
        for y in range(self.board_height):
            for x in range(self.board_width):
                if self.board[y][x] != '':
                    print(str(x) + 'x' + str(y) +
                          ' - ' + str(self.board[y][x]))
                    painter.setPen(Qt.red)
                    painter.drawRect(x, y, 1, 1)
                else:
                    painter.setPen(Qt.black)
                    painter.drawRect(x, y, 1, 1)

        self.update()

    def drawPlayer(self, painter):

        painter.drawPixmap(
            self.player_x,
            self.player_y,
            self.player_size,
            self.player_size,
            self.use_this_pixmap
        )

    def heuristic(self, a, b):
        (x1, y1) = a
        (x2, y2) = b
        return abs(x1 - x2) + abs(y1 - y2)

    def dijkstraSearch(self, graph, start, goal):
        """
        Algorytm Dijkstry
        """
        steps = PriorityQueue()
        steps.put(start, 0)
        cameFrom = {}
        costSoFar = {}
        cameFrom[start] = None
        costSoFar[start] = 0

        # dopoki cos w liscie krokow
        while not steps.empty():
            # pozyskaj miejsce, w ktorym jestes
            current = steps.get()

            # jesli dotarles do celu, to przerwij
            if current == goal:
                break

            # dla kazdego z sasiadow
            for next in graph.neighbours(current):
                # oblicz nowy koszt dojscia (dotychczasowy + do sasiada)
                newCost = costSoFar[current] + graph.cost(current, next)
                # jezeli koszt nie istnial wczesniej
                # lub jest nizszy niz poprzednik
                # to umiesc go w liscie kosztow do nastepnego kroku
                if next not in costSoFar or newCost < costSoFar[next]:
                    costSoFar[next] = newCost
                    # jako priorytet ustaw koszt
                    priority = newCost
                    steps.put(next, priority)
                    cameFrom[next] = current

        # zwroc koszt dojscia i liste krokow (lista od konca)
        return cameFrom, costSoFar

    def aStarSearch(self, graph, start, goal):
        frontier = PriorityQueue()
        frontier.put(start, 0)
        came_from = {}
        cost_so_far = {}
        came_from[start] = None
        cost_so_far[start] = 0

        while not frontier.empty():
            current = frontier.get()

            if current == goal:
                break

            for next in graph.neighbours(current):
                new_cost = cost_so_far[current] + graph.cost(current, next)
                if next not in cost_so_far or new_cost < cost_so_far[next]:
                    cost_so_far[next] = new_cost
                    priority = new_cost + self.heuristic(goal, next)
                    frontier.put(next, priority)
                    came_from[next] = current

        return came_from, cost_so_far

    def reconstructPath(self, came_from, start, goal):
        current = goal
        path = [current]
        while current != start:
            current = came_from[current]
            path.append(current)
        path.reverse()
        return path

    def draw_tile(self, graph, id, style, width):
        r = "."
        if 'number' in style and id in style['number']:
            r = "%d" % style['number'][id]
        if ('point_to' in style and
                style['point_to'].get(id, None) is not None):
            (x1, y1) = id
            (x2, y2) = style['point_to'][id]
            if x2 == x1 + 1:
                r = "\u2192"
            if x2 == x1 - 1:
                r = "\u2190"
            if y2 == y1 + 1:
                r = "\u2193"
            if y2 == y1 - 1:
                r = "\u2191"
        if 'start' in style and id == style['start']:
            r = "A"
        if 'goal' in style and id == style['goal']:
            r = "Z"
        if 'path' in style and id in style['path']:
            r = "@"
        if id in graph.walls:
            r = "#" * width
        return r

    def draw_grid(self, graph, width=2, **style):
        for y in range(graph.height):
            for x in range(graph.width):
                print("%%-%ds" % width % self.draw_tile(graph, (x, y),
                      style, width), end="")
            print()

    @pyqtSlot(str)
    def goTo(self, position):
        x, y = position.split()

        pointX = int(int(x) / 80)
        pointY = int(int(y) / 80)

        playerX = int(self.player_x / 80)
        playerY = int(self.player_y / 80)

        if self.pathFinding == "aStar":
            cameFrom, costSoFar = self.aStarSearch(self.graph,
                                                  (playerX, playerY),
                                                  (pointX, pointY))
        elif self.pathFinding == "dijkstra":
            cameFrom, costSoFar = self.dijkstraSearch(self.graph,
                                                     (playerX, playerY),
                                                     (pointX, pointY))

        self.path = self.reconstructPath(cameFrom,
            (playerX, playerY),
            (pointX, pointY))
        self.movePlayer()
예제 #30
0
class HAdjustmentBar(QWidget):
    valueChanged = pyqtSignal(int)
    def __init__(self, parent=None):
        super(HAdjustmentBar, self).__init__(parent)
        self.value = 50
        self.step = 1
        self.hi_value = 100
        self.low_value = 50
        self.timer_value = 100
        self.texttemplate = 'Value =  %s'
        self.timer = QBasicTimer()
        self.showToggleButton = True
        self.showSettingMenu = True
        self.bar = LabeledBar()
        #self.bar.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
        # black magic class patching
        # so calling these functions actually calls the self.bar's functions.
        self.minimum = self.bar.minimum
        self.maximum = self.bar.maximum

    def buildWidget(self):
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0,0,0,0)
        SettingMenu = QMenu()
        exitButton = QAction(QIcon('exit24.png'), 'Set As High', self)
        exitButton.triggered.connect(self.setHigh)
        SettingMenu.addAction(exitButton)
        setlowButton = QAction(QIcon('exit24.png'), 'Set As Low', self)
        setlowButton.triggered.connect(self.setLow)
        SettingMenu.addAction(setlowButton)

        self.tb_down = QToolButton()
        self.tb_down.pressed.connect(self.on_click_down)
        self.tb_down.released.connect(self.on_released)
        self.tb_down.setArrowType(Qt.LeftArrow)

        self.tb_up = QToolButton()
        self.tb_up.pressed.connect(self.on_click_up)
        self.tb_up.released.connect(self.on_released)
        self.tb_up.setArrowType(Qt.RightArrow)

        if self.showToggleButton:
            tb_set = QToolButton()
            tb_set.clicked.connect(self.on_click_set_value)
            tb_set.setText('<>')
            if self.showSettingMenu:
                tb_set.setMenu(SettingMenu)
                tb_set.setPopupMode(QToolButton.DelayedPopup)

        layout.addWidget(self.tb_down)
        layout.addWidget(self.bar)
        layout.addWidget(self.tb_up)
        if self.showToggleButton:
            layout.addWidget(tb_set)
        layout.setSpacing(0)

    def on_click_up(self):
        self.timer.start(self.timer_value, self)
        self.value += self.step
        self._setValue()

    def on_click_down(self):
        self.timer.start(self.timer_value, self)
        self.value -= self.step
        self._setValue()
    def on_released(self):
        self.timer.stop()

    def on_click_set_value(self):
        if self.value == self.hi_value:
            self.value = self.low_value
        else:
            self.value = self.hi_value
        self._setValue()

    def timerEvent(self, e):
        if self.value < self.maximum() and self.value > self.minimum():
            if self.tb_down.isDown():
                self.value -= self.step
            else:
                self.value += self.step
            self._setValue()
        else:
            self.timer.stop()

    def _setValue(self):
        if self.value < self.minimum():self. value = self.minimum()
        if self.value > self.maximum(): self.value = self.maximum()
        self.valueChanged.emit(self.value)

    def setValue(self, value):
        if value < self.minimum(): value = self.minimum()
        if value > self.maximum(): value = self.maximum()
        self.value = int(value)
        tmpl = lambda s: self.texttemplate % s
        try:
            self.bar.text = tmpl(int(value))
        except:
            self.bar.text = self.texttemplate
        self.bar.setValue(int(value))
        self.bar.update()

    def setHigh(self):
        self.hi_value = self.value

    def setLow(self):
        self.low_value = self.value

    def setMaximum(self, data):
        if data < self.hi_value:
            self.hi_value = data
        self.bar.setMaximum(data)

    def setMinimum(self, data):
        if data > self.low_value:
            self.low_value = data
        self.bar.setMinimum(data)

    def setStep(self, data):
        self.step = data
예제 #31
0
class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()


    def initUI(self):

        # checkbox
        cb = QCheckBox('show title', self)
        cb.move(20, 20)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)

        # toggle button
        self.col = QColor(0, 0, 0)

        redb = QPushButton('red', self)
        redb.setCheckable(True)
        redb.move(20, 40)
        redb.clicked[bool].connect(self.setColor)

        greenb = QPushButton('green', self)
        greenb.setCheckable(True)
        greenb.move(20, 60)
        greenb.clicked[bool].connect(self.setColor)

        blueb = QPushButton('blue', self)
        blueb.setCheckable(True)
        blueb.move(20, 80)
        blueb.clicked[bool].connect(self.setColor)

        self.square = QFrame(self)
        self.square.setGeometry(150, 20, 100, 100)
        self.square.setStyleSheet('QWidget {background-color: %s}' %
            self.col.name())

        # slider
        sld = QSlider(Qt.Horizontal, self)
        sld.setFocusPolicy(Qt.NoFocus)
        sld.setGeometry(20, 160, 100, 20)
        sld.valueChanged[int].connect(self.changeValue)

        self.label = QLabel('0', self)
        self.label.setGeometry(140, 155, 80, 30)

        # progressbar
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(20, 200, 200, 25)

        self.btn = QPushButton('start', self)
        self.btn.move(20, 230)
        self.btn.clicked.connect(self.doAction)

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

        # calendar
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.move(20, 300)
        cal.clicked[QDate].connect(self.showDate)

        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(20, 280)

        self.setGeometry(300, 300, 400, 550)
        self.setWindowTitle('widgets')
        self.show()

    def showDate(self, date):
        self.lbl.setText(date.toString())

    def timerEvent(self, e):

        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()
        else:
            self.timer.start(100, self)
            self.btn.setText('stop')

    def changeValue(self, value):
        self.label.setText(str(value))

    def setColor(self, pressed):
        source = self.sender()

        if pressed:
            val = 255
        else:
            val = 0

        if source.text() == 'red':
            self.col.setRed(val)
        elif source.text() == 'green':
            self.col.setGreen(val)
        else:
            self.col.setBlue(val)

        self.square.setStyleSheet('QFrame {background-color: %s}' %
            self.col.name())


    def changeTitle(self, state):
        if state == Qt.Checked:
            self.setWindowTitle('widgets')
        else:
            self.setWindowTitle('')
예제 #32
0
파일: coordapp.py 프로젝트: thet0mmy/attic
class MouseFollower(QWidget):
    def __init__(self, *args):
        super(MouseFollower, self).__init__(*args)

        self.following = False
        self.grabbing = False
        self.cursorTimer = QBasicTimer()

    def isGrabbing(self):
        return self.grabbing

    def isFollowing(self):
        return self.following

    mouseMoved = Signal(QPoint)
    clickWhileGrabbed = Signal()

    @Slot()
    def toggleGrab(self):
        refollow = self.following

        if refollow:
            self.endFollow()
        self.grabbing = not self.grabbing

        if refollow:
            self.startFollow()

    def toggleFollow(self):
        if self.following:
            self.endFollow()
        else:
            self.startFollow()

    @Slot()
    def startFollow(self):
        if not self.grabbing:
            self.cursorTimer.start(100, self)
        else:
            self.setMouseTracking(True)
            self.grabMouse()
        self.following = True

    @Slot()
    def endFollow(self):
        if not self.grabbing:
            self.cursorTimer.stop()
        else:
            self.releaseMouse()
        self.following = False

    def timerEvent(self, ev):
        if ev.timerId() == self.cursorTimer.timerId():
            self.mouseMoved.emit(QCursor.pos())
        else:
            super(MouseFollower, self).timerEvent(ev)

    def mouseMoveEvent(self, ev):
        self.mouseMoved.emit(QCursor.pos())
        return super(MouseFollower, self).mouseMoveEvent(ev)

    def mousePressEvent(self, ev):
        if self.grabbing:
            self.clickWhileGrabbed.emit()
        return super(MouseFollower, self).mousePressEvent(ev)
예제 #33
0
class WidgetCode(QLabel):
    def __init__(self, *args, **kwargs):
        super(WidgetCode, self).__init__(*args, **kwargs)
        self._sensitive = False  # 是否大小写敏感
        self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.setBackgroundRole(QPalette.Midlight)
        self.setAutoFillBackground(True)
        # 字体
        newFont = self.font()
        newFont.setPointSize(16)
        newFont.setFamily("Kristen ITC")
        newFont.setBold(True)
        self.setFont(newFont)
        self.reset()
        # 定时器
        self.step = 0
        self.timer = QBasicTimer()
        self.timer.start(60, self)

    def reset(self):
        self._code = "".join(sample(WORDS, 4))  # 随机4个字符
        self.setText(self._code)

    def check(self, code):
        return self._code == str(
            code) if self._sensitive else self._code.lower() == str(
                code).lower()

    def setSensitive(self, sensitive):
        self._sensitive = sensitive


#     def setText(self, text):
#         text = text if (text and len(text) == 4) else "".join(sample(WORDS, 4))  # 随机4个字符
#         self._code = str(text)
#         html = "".join([FONT.format(color=COLORLIST[qrand() % 6], word=t) for t in text])
#         super(WidgetCode, self).setText(HTML.format(html=html))

    def mouseReleaseEvent(self, event):
        super(WidgetCode, self).mouseReleaseEvent(event)
        self.reset()

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            self.step += 1
            return self.update()
        return super(WidgetCode, self).timerEvent(event)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        # 背景白色
        painter.fillRect(event.rect(), QBrush(Qt.white))
        # 绘制边缘虚线框
        painter.setPen(Qt.DashLine)
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(self.rect())
        # 随机画条线
        for _ in range(3):
            painter.setPen(QPen(QTCOLORLIST[qrand() % 5], 1, Qt.SolidLine))
            painter.setBrush(Qt.NoBrush)
            painter.drawLine(QPoint(0,
                                    qrand() % self.height()),
                             QPoint(self.width(),
                                    qrand() % self.height()))
            painter.drawLine(QPoint(qrand() % self.width(), 0),
                             QPoint(qrand() % self.width(), self.height()))
        # 绘制噪点
        painter.setPen(Qt.DotLine)
        painter.setBrush(Qt.NoBrush)
        for _ in range(self.width()):  # 绘制噪点
            painter.drawPoint(
                QPointF(qrand() % self.width(),
                        qrand() % self.height()))
        # super(WidgetCode, self).paintEvent(event)  # 绘制文字
        # 绘制跳动文字
        metrics = QFontMetrics(self.font())
        x = (self.width() - metrics.width(self.text())) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        for i, ch in enumerate(self.text()):
            index = (self.step + i) % 16
            painter.setPen(TCOLORLIST[qrand() % 6])
            painter.drawText(x,
                             y - ((SINETABLE[index] * metrics.height()) / 400),
                             ch)
            x += metrics.width(ch)
예제 #34
0
class Ui_manager_face(QWidget):
    def __init__(self):
        super(Ui_manager_face, self).__init__()

        # 初始化 ID
        self.ID_num = ""
        self.lab_face = QLabel(self)

        # 初始化进度条定时器
        self.timer = QBasicTimer()
        self.step = 0

        # 创建数字按键
        self.btn_1 = QPushButton('1', self)
        self.btn_2 = QPushButton('2', self)
        self.btn_3 = QPushButton('3', self)
        self.btn_4 = QPushButton('4', self)
        self.btn_5 = QPushButton('5', self)
        self.btn_6 = QPushButton('6', self)
        self.btn_7 = QPushButton('7', self)
        self.btn_8 = QPushButton('8', self)
        self.btn_9 = QPushButton('9', self)
        self.btn_0 = QPushButton('0', self)
        self.btn_del = QPushButton('del', self)

        # 创建容器存放数字键,使用栅格布局
        self.layoutWidget = QWidget(self)
        self.gridLayout = QGridLayout(self.layoutWidget)

        # 创建groupBox控件
        self.groupBox = QtWidgets.QGroupBox(self)

        # 创建lab_ID控件
        self.lab_ID = QLabel(self.groupBox)
        self.Edit_ID = QLineEdit(self.groupBox)
        self.btn_enter = QPushButton(self.groupBox)
        self.progressBar = QtWidgets.QProgressBar(self.groupBox)
        self.btn_back = QPushButton(self)

        # 创建定时器
        self.timer_camera = QtCore.QTimer()

        # 初始化摄像头数据
        self.camera_init()

        # 初始化界面
        self.init_ui()

        # 显示人脸识别视频界面
        self.face_rec()

        # 定时器函数
        self.timer_camera.timeout.connect(self.show_camera)

        # 点击按钮开启线程
        self.btn_enter.clicked.connect(self.slot_btn_enter)

    # 初始化摄像头数据
    def camera_init(self):
        # 打开设置摄像头对象
        self.cap = cv2.VideoCapture()
        self.CAM_NUM = 0
        self.__flag_work = 0
        self.x = 0
        self.count = 0
        self.cap.set(4, 951)  # set Width
        self.cap.set(3, 761)  # set Height

    # 初始化界面
    def init_ui(self):
        self.resize(1280, 800)
        self.lab_face.setGeometry(15, 40, 960, 720)
        self.lab_face.setFrameShape(QtWidgets.QFrame.Box)
        self.lab_face.setText("")
        self.lab_ID.setGeometry(10, 40, 31, 41)

        # 设置容器位置
        self.layoutWidget.setGeometry(1010, 350, 231, 251)

        # 设置数字键高度
        self.btn_0.setFixedHeight(50)
        self.btn_1.setFixedHeight(50)
        self.btn_2.setFixedHeight(50)
        self.btn_3.setFixedHeight(50)
        self.btn_4.setFixedHeight(50)
        self.btn_5.setFixedHeight(50)
        self.btn_6.setFixedHeight(50)
        self.btn_7.setFixedHeight(50)
        self.btn_8.setFixedHeight(50)
        self.btn_9.setFixedHeight(50)
        self.btn_del.setFixedHeight(50)

        # 对数字按键字体大小进行设置
        self.btn_1.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_2.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_3.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_4.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_5.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_6.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_7.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_8.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_9.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_0.setStyleSheet("QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
                                 "font-size:30px;"  # 大小为30 
                                 "font-family:Roman times;}")  # Roman times字体
        self.btn_del.setStyleSheet(
            "QPushButton{color:rgb(0,0,0,255);"  # 字体颜色为黑色
            "font-size:30px;"  # 大小为30 
            "font-family:Roman times;}")  # Roman times字体

        # 将数字存放进容器
        self.gridLayout.addWidget(self.btn_1, 0, 0, 1, 1)
        self.gridLayout.addWidget(self.btn_2, 0, 1, 1, 1)
        self.gridLayout.addWidget(self.btn_3, 0, 2, 1, 1)
        self.gridLayout.addWidget(self.btn_4, 1, 0, 1, 1)
        self.gridLayout.addWidget(self.btn_5, 1, 1, 1, 1)
        self.gridLayout.addWidget(self.btn_6, 1, 2, 1, 1)
        self.gridLayout.addWidget(self.btn_7, 2, 0, 1, 1)
        self.gridLayout.addWidget(self.btn_8, 2, 1, 1, 1)
        self.gridLayout.addWidget(self.btn_9, 2, 2, 1, 1)
        self.gridLayout.addWidget(self.btn_0, 3, 0, 1, 1)
        self.gridLayout.addWidget(self.btn_del, 3, 1, 1, 2)

        # 对groupBox进行设置
        self.groupBox.setTitle("录入人脸")
        self.groupBox.setGeometry(990, 120, 281, 191)
        self.groupBox.setStyleSheet("QGroupBox {\n"
                                    "border-width:2px;\n"
                                    "border-style:solid;\n"
                                    "border-color:lightGray;\n"
                                    "font: 75 20pt \"Aharoni\";\n"
                                    "margin-top: 0.5ex;\n"
                                    "}\n"
                                    "QGroupBox::title {\n"
                                    "subcontrol-origin: margin;\n"
                                    "subcontrol-position: top left;\n"
                                    "left:10px;\n"
                                    "margin-left: 0px;\n"
                                    "padding:0px;\n"
                                    "}")

        # 设置groupBox里面的控件
        self.lab_ID.setText("ID")
        self.lab_ID.setGeometry(10, 40, 31, 41)
        self.lab_ID.setStyleSheet("font: 18pt;")

        self.Edit_ID.setGeometry(50, 40, 221, 41)
        self.Edit_ID.setStyleSheet("font: 18pt;")

        self.btn_enter.setText("开始录入")
        self.btn_enter.setGeometry(80, 90, 121, 51)
        self.btn_enter.setStyleSheet("font: 75 16pt;")

        self.progressBar.setGeometry(10, 150, 261, 31)
        # self.progressBar.setProperty("value", 0)

        self.btn_back.setText("返回")
        self.btn_back.setGeometry(1090, 670, 81, 51)
        self.btn_back.setStyleSheet("font: 75 16pt;")

        # 点击数字按钮输入用户名和密码
        self.btn_0.clicked.connect(self.slot_btn_0)
        self.btn_1.clicked.connect(self.slot_btn_1)
        self.btn_2.clicked.connect(self.slot_btn_2)
        self.btn_3.clicked.connect(self.slot_btn_3)
        self.btn_4.clicked.connect(self.slot_btn_4)
        self.btn_5.clicked.connect(self.slot_btn_5)
        self.btn_6.clicked.connect(self.slot_btn_6)
        self.btn_7.clicked.connect(self.slot_btn_7)
        self.btn_8.clicked.connect(self.slot_btn_8)
        self.btn_9.clicked.connect(self.slot_btn_9)
        self.btn_del.clicked.connect(self.slot_btn_del)

        # 点击返回按键返回上一界面
        self.btn_back.clicked.connect(self.slot_btn_back)

    # 点击数字按钮输入用户名和密码
    def slot_btn_0(self):
        ID_num0 = self.btn_0.text()
        self.ID_num = self.ID_num + ID_num0
        self.Edit_ID.setText(self.ID_num)

    def slot_btn_1(self):
        ID_num1 = self.btn_1.text()
        self.ID_num = self.ID_num + ID_num1
        self.Edit_ID.setText(self.ID_num)

    def slot_btn_2(self):
        ID_num2 = self.btn_2.text()
        self.ID_num = self.ID_num + ID_num2
        self.Edit_ID.setText(self.ID_num)

    def slot_btn_3(self):
        ID_num3 = self.btn_3.text()
        self.ID_num = self.ID_num + ID_num3
        self.Edit_ID.setText(self.ID_num)

    def slot_btn_4(self):
        ID_num4 = self.btn_4.text()
        self.ID_num = self.ID_num + ID_num4
        self.Edit_ID.setText(self.ID_num)

    def slot_btn_5(self):
        ID_num5 = self.btn_5.text()
        self.ID_num = self.ID_num + ID_num5
        self.Edit_ID.setText(self.ID_num)

    def slot_btn_6(self):
        ID_num6 = self.btn_6.text()
        self.ID_num = self.ID_num + ID_num6
        self.Edit_ID.setText(self.ID_num)

    def slot_btn_7(self):
        ID_num7 = self.btn_7.text()
        self.ID_num = self.ID_num + ID_num7
        self.Edit_ID.setText(self.ID_num)

    def slot_btn_8(self):
        ID_num8 = self.btn_8.text()
        self.ID_num = self.ID_num + ID_num8
        self.Edit_ID.setText(self.ID_num)

    def slot_btn_9(self):
        ID_num9 = self.btn_9.text()
        self.ID_num = self.ID_num + ID_num9
        self.Edit_ID.setText(self.ID_num)

    # 将字符串从最后一位开始删除
    def slot_btn_del(self):
        self.ID_num = self.ID_num[:-1]
        self.Edit_ID.setText(self.ID_num)

    # 点击返回按键返回上一界面
    def slot_btn_back(self):
        self.logon = Ui_logon()
        self.logon.show()
        self.timer_camera.stop()
        self.cap.release()
        self.hide()

    # 显示人脸识别视频界面
    def face_rec(self):
        if self.timer_camera.isActive() == False:
            flag = self.cap.open(self.CAM_NUM)
            if flag == False:
                msg = QtWidgets.QMessageBox.warning(
                    self,
                    u"Warning",
                    u"请检测相机与电脑是否连接正确",
                    buttons=QtWidgets.QMessageBox.Ok,
                    defaultButton=QtWidgets.QMessageBox.Ok)
            else:
                self.timer_camera.start(30)
        else:
            self.timer_camera.stop()
            self.cap.release()

    def show_camera(self):
        flag, self.image = self.cap.read()
        self.image = cv2.flip(self.image, -1)
        gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
        faces = faceCascade.detectMultiScale(gray,
                                             scaleFactor=1.2,
                                             minNeighbors=5,
                                             minSize=(20, 20))
        for (x, y, w, h) in faces:
            cv2.rectangle(self.image, (x, y), (x + w, y + h), (255, 0, 0), 2)
            roi_gray = gray[y:y + h, x:x + w]
            roi_color = self.image[y:y + h, x:x + w]

        # 将视频显示在了label上
        show = cv2.resize(self.image, (960, 720))
        show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
        showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0],
                                 QtGui.QImage.Format_RGB888)
        self.lab_face.setPixmap(QtGui.QPixmap.fromImage(showImage))

    # 点击按钮开启线程
    def slot_btn_enter(self):
        self.count = 0
        self.step = 0
        # 创建线程并开启
        self.thread = threading.Thread(target=self.thread_pic)
        self.thread.start()

        # 开启进度条定时器
        self.timer.start(100, self)

    # 加载进度条
    def timerEvent(self, e):
        if self.step > 58:
            self.timer.stop()
            return
        self.step = self.count + 1
        self.progressBar.setValue(self.count)

    # 录入人脸线程
    def thread_pic(self):
        print("线程出没!!!")
        print(self.Edit_ID.text())

        # 创建目录,将获取的人脸照片放入指定的文件夹
        self.file = "./Face_data/"

        while (True):
            ret, self.img = self.cap.read()
            # 垂直翻转视频图像
            self.img = cv2.flip(self.img, -1)
            # 灰度化处理
            gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
            faces = faceCascade2.detectMultiScale(gray, 1.3, 5)

            # 判断是否存在文件夹如果不存在则创建为文件夹
            self.folder = os.path.exists(self.file)
            if not self.folder:
                # makedirs 满权限创建文件时如果路径不存在会创建这个路径
                os.makedirs(self.file)
                os.chmod(self.file, 0777)

            for (x, y, w, h) in faces:
                cv2.rectangle(self.img, (x, y), (x + w, y + h), (255, 0, 0), 2)
                self.count += 1
                # 将捕获的图像保存到指定的文件夹中
                bool = cv2.imwrite(
                    self.file + "/User." + str(self.Edit_ID.text()) + '.' +
                    str(self.count) + ".png", gray[y:y + h, x:x + w])

            # 取60张人脸样本,停止录像
            if self.count >= 60:
                print("OK!")
                break
        self.recognizer = cv2.face.LBPHFaceRecognizer_create()

        # 函数获取图像和标签数据
        def getImagesAndLabels(path):
            imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
            faceSamples = []
            ids = []
            self.progressBar.setProperty("value", 65)
            for imagePath in imagePaths:
                # 转换为灰度
                PIL_img = Image.open(imagePath).convert('L')
                img_numpy = np.array(PIL_img, 'uint8')
                id = int(os.path.split(imagePath)[-1].split(".")[1])

                faces = faceCascade3.detectMultiScale(img_numpy)
                for (x, y, w, h) in faces:
                    faceSamples.append(img_numpy[y:y + h, x:x + w])
                    ids.append(id)
            return faceSamples, ids

        self.progressBar.setProperty("value", 75)
        print("\n [INFO] Training faces. It will take a few seconds. Wait ...")

        # 调用函数,传递文件夹路径参数
        faces, ids = getImagesAndLabels(self.file)
        self.recognizer.train(faces, np.array(ids))
        self.progressBar.setProperty("value", 85)

        # 创建文件夹
        self.triningfile = "./Face_training/"
        self.folder1 = os.path.exists(self.triningfile)
        if not self.folder1:
            os.makedirs(self.triningfile)
            os.chmod(self.triningfile, 0777)

        # 将训练好的数据保存到指定文件夹中
        self.recognizer.write(self.triningfile + "/trainer.yml")

        # 打印经过训练的人脸编号和结束程序
        print("\n [INFO] {0} faces trained. Exiting Program".format(
            len(np.unique(ids))))
        self.progressBar.setProperty("value", 100)
예제 #35
0
class TetrixBoard(QFrame):
    BoardWidth = 10
    BoardHeight = 22

    scoreChanged = pyqtSignal(int)

    levelChanged = pyqtSignal(int)

    linesRemovedChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        super(TetrixBoard, self).__init__(parent)

        self.timer = QBasicTimer()
        self.nextPieceLabel = None
        self.isWaitingAfterLine = False
        self.curPiece = TetrixPiece()
        self.nextPiece = TetrixPiece()
        self.curX = 0
        self.curY = 0
        self.numLinesRemoved = 0
        self.numPiecesDropped = 0
        self.score = 0
        self.level = 0
        self.board = None

        self.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.setFocusPolicy(Qt.StrongFocus)
        self.isStarted = False
        self.isPaused = False
        self.clearBoard()

        self.nextPiece.setRandomShape()

    def shapeAt(self, x, y):
        return self.board[(y * TetrixBoard.BoardWidth) + x]

    def setShapeAt(self, x, y, shape):
        self.board[(y * TetrixBoard.BoardWidth) + x] = shape

    def timeoutTime(self):
        return 1000 / (1 + self.level)

    def squareWidth(self):
        return self.contentsRect().width() / TetrixBoard.BoardWidth

    def squareHeight(self):
        return self.contentsRect().height() / TetrixBoard.BoardHeight

    def setNextPieceLabel(self, label):
        self.nextPieceLabel = label

    def sizeHint(self):
        return QSize(TetrixBoard.BoardWidth * 15 + self.frameWidth() * 2,
                     TetrixBoard.BoardHeight * 15 + self.frameWidth() * 2)

    def minimumSizeHint(self):
        return QSize(TetrixBoard.BoardWidth * 5 + self.frameWidth() * 2,
                     TetrixBoard.BoardHeight * 5 + self.frameWidth() * 2)

    def start(self):
        if self.isPaused:
            return

        self.isStarted = True
        self.isWaitingAfterLine = False
        self.numLinesRemoved = 0
        self.numPiecesDropped = 0
        self.score = 0
        self.level = 1
        self.clearBoard()

        self.linesRemovedChanged.emit(self.numLinesRemoved)
        self.scoreChanged.emit(self.score)
        self.levelChanged.emit(self.level)

        self.newPiece()
        self.timer.start(self.timeoutTime(), self)

    def pause(self):
        if not self.isStarted:
            return

        self.isPaused = not self.isPaused
        if self.isPaused:
            self.timer.stop()
        else:
            self.timer.start(self.timeoutTime(), self)

        self.update()

    def paintEvent(self, event):
        super(TetrixBoard, self).paintEvent(event)

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

        if self.isPaused:
            painter.drawText(rect, Qt.AlignCenter, "Pause")
            return

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

        for i in range(TetrixBoard.BoardHeight):
            for j in range(TetrixBoard.BoardWidth):
                shape = self.shapeAt(j, TetrixBoard.BoardHeight - i - 1)
                if shape != NoShape:
                    self.drawSquare(painter,
                                    rect.left() + j * self.squareWidth(),
                                    boardTop + i * self.squareHeight(), shape)

        if self.curPiece.shape() != 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 +
                    (TetrixBoard.BoardHeight - y - 1) * self.squareHeight(),
                    self.curPiece.shape())

    def keyPressEvent(self, event):
        if not self.isStarted or self.isPaused or self.curPiece.shape(
        ) == NoShape:
            super(TetrixBoard, self).keyPressEvent(event)
            return

        key = event.key()
        if 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.rotatedRight(), self.curX, self.curY)
        elif key == Qt.Key_Up:
            self.tryMove(self.curPiece.rotatedLeft(), self.curX, self.curY)
        elif key == Qt.Key_Space:
            self.dropDown()
        elif key == Qt.Key_D:
            self.oneLineDown()
        else:
            super(TetrixBoard, self).keyPressEvent(event)

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            if self.isWaitingAfterLine:
                self.isWaitingAfterLine = False
                self.newPiece()
                self.timer.start(self.timeoutTime(), self)
            else:
                self.oneLineDown()
        else:
            super(TetrixBoard, self).timerEvent(event)

    def clearBoard(self):
        self.board = [
            NoShape
            for i in range(TetrixBoard.BoardHeight * TetrixBoard.BoardWidth)
        ]

    def dropDown(self):
        dropHeight = 0
        newY = self.curY
        while newY > 0:
            if not self.tryMove(self.curPiece, self.curX, newY - 1):
                break
            newY -= 1
            dropHeight += 1

        self.pieceDropped(dropHeight)

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

    def pieceDropped(self, dropHeight):
        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.numPiecesDropped += 1
        if self.numPiecesDropped % 25 == 0:
            self.level += 1
            self.timer.start(self.timeoutTime(), self)
            self.levelChanged.emit(self.level)

        self.score += dropHeight + 7
        self.scoreChanged.emit(self.score)
        self.removeFullLines()

        if not self.isWaitingAfterLine:
            self.newPiece()

    def removeFullLines(self):
        numFullLines = 0

        for i in range(TetrixBoard.BoardHeight - 1, -1, -1):
            lineIsFull = True

            for j in range(TetrixBoard.BoardWidth):
                if self.shapeAt(j, i) == NoShape:
                    lineIsFull = False
                    break

            if lineIsFull:
                numFullLines += 1
                for k in range(TetrixBoard.BoardHeight - 1):
                    for j in range(TetrixBoard.BoardWidth):
                        self.setShapeAt(j, k, self.shapeAt(j, k + 1))

                for j in range(TetrixBoard.BoardWidth):
                    self.setShapeAt(j, TetrixBoard.BoardHeight - 1, NoShape)

        if numFullLines > 0:
            self.numLinesRemoved += numFullLines
            self.score += 10 * numFullLines
            self.linesRemovedChanged.emit(self.numLinesRemoved)
            self.scoreChanged.emit(self.score)

            self.timer.start(500, self)
            self.isWaitingAfterLine = True
            self.curPiece.setShape(NoShape)
            self.update()

    def newPiece(self):
        self.curPiece = copy.deepcopy(self.nextPiece)
        self.nextPiece.setRandomShape()
        self.showNextPiece()
        self.curX = TetrixBoard.BoardWidth // 2 + 1
        self.curY = TetrixBoard.BoardHeight - 1 + self.curPiece.minY()

        if not self.tryMove(self.curPiece, self.curX, self.curY):
            self.curPiece.setShape(NoShape)
            self.timer.stop()
            self.isStarted = False

    def showNextPiece(self):
        if self.nextPieceLabel is None:
            return

        dx = self.nextPiece.maxX() - self.nextPiece.minX() + 1
        dy = self.nextPiece.maxY() - self.nextPiece.minY() + 1

        pixmap = QPixmap(dx * self.squareWidth(), dy * self.squareHeight())
        painter = QPainter(pixmap)
        painter.fillRect(pixmap.rect(), self.nextPieceLabel.palette().window())

        for i in range(4):
            x = self.nextPiece.x(i) - self.nextPiece.minX()
            y = self.nextPiece.y(i) - self.nextPiece.minY()
            self.drawSquare(painter, x * self.squareWidth(),
                            y * self.squareHeight(), self.nextPiece.shape())

        painter.end()

        self.nextPieceLabel.setPixmap(pixmap)

    def tryMove(self, newPiece, newX, newY):
        for i in range(4):
            x = newX + newPiece.x(i)
            y = newY - newPiece.y(i)
            if x < 0 or x >= TetrixBoard.BoardWidth or y < 0 or y >= TetrixBoard.BoardHeight:
                return False
            if self.shapeAt(x, y) != NoShape:
                return False

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

    def drawSquare(self, painter, x, y, 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)
예제 #36
0
class FieldUI(QFrame):
    def __init__(self, parent, game):
        super().__init__(parent)
        self.main_window = parent
        self.game = game
        self.rocks = self.game.rocks
        self.powerups = self.game.powerups
        self.bullets = self.game.bullets
        self.width, self.height = self.game.dimensions

        self.init_timers()
        self.start_timers()

        self.player_ui = PlayerUI(self, self.game)

        self.init_signals()
        self.setFocusPolicy(Qt.StrongFocus)

    def init_timers(self):
        """Initializes the timers in the game."""
        self.game_timer = QBasicTimer()
        self.rock_timer = QBasicTimer()
        self.level_timer = QBasicTimer()
        self.powerup_timer = QBasicTimer()
        self.ticker_timer = QBasicTimer()
        self.bullet_timer = QBasicTimer()

        self.player_invincibility_timer = QBasicTimer()
        self.big_bomb_timer = QBasicTimer()
        self.slow_down_rocks_timer = QBasicTimer()
        self.shoot_rocks_timer = QBasicTimer()

        self.powerup_duration_timer = QTimer()

    def start_timers(self):
        """Starts the timers in the game."""
        self.game_timer.start(self.game.game_speed, self)
        self.rock_timer.start(self.game.rock_speed, self)
        self.level_timer.start(self.game.level_speed, self)
        self.powerup_timer.start(self.game.rock_speed, self)
        self.player_invincibility_timer.start(int(PowerupTimeInterval.medium),
                                              self)
        self.big_bomb_timer.start(int(PowerupTimeInterval.big), self)
        self.slow_down_rocks_timer.start(int(PowerupTimeInterval.medium), self)
        self.shoot_rocks_timer.start(int(PowerupTimeInterval.very_big), self)
        self.bullet_timer.start(self.game.bullet_speed, self)

    def stop_timers(self):
        """Stops the timers in the game."""
        self.game_timer.stop()
        self.rock_timer.stop()
        self.level_timer.stop()
        self.powerup_timer.stop()
        self.ticker_timer.stop()
        self.bullet_timer.stop()

        self.player_invincibility_timer.stop()
        self.big_bomb_timer.stop()
        self.slow_down_rocks_timer.stop()
        self.shoot_rocks_timer.stop()

        self.powerup_duration_timer.stop()

    def init_signals(self):
        """Initializes the signals in the game that connect to a method and
        calls it after the singnals are emitted.
        """
        self.com = Communicate()
        self.com.move_left.connect(self.player_ui.move_left)
        self.com.move_right.connect(self.player_ui.move_right)
        self.com.restart.connect(self.main_window.restart_game)
        self.com.exit.connect(UserInterface.close_app)
        self.com.win.connect(self.win_the_game)

    def timerEvent(self, event):
        """Gets the emitted events from the timers and calls the appropriate
        methods for each of them.
        """
        self.powerups_timer_events(event)
        self.gameplay_timer_events(event)
        if event.timerId() == self.ticker_timer.timerId():
            self.ticker["value"] -= 1
            if self.ticker["type"] == "player_invincibility":
                self.show_player_invincibility_info(self.ticker["value"])
            if self.ticker["type"] == "slow_down_rocks":
                self.show_slow_down_rocks_info(self.ticker["value"])
            if self.ticker["type"] == "shoot_rocks":
                self.show_shoot_rocks_info(self.ticker["value"])
                self.bullet_ui = BulletUI(self, self.game, self.player_ui)
                self.bullets.append(self.bullet_ui)
        else:
            super(FieldUI, self).timerEvent(event)

    def gameplay_timer_events(self, event):
        """Gets the emitted events from the timers related to the gameplay and
        calls the appropriate methods and initializes the appropriate objects
        for each of them.
        """
        if event.timerId() == self.game_timer.timerId():
            self.rock_ui = RockUI(self, self.game)
            self.rocks.append(self.rock_ui)
        elif event.timerId() == self.rock_timer.timerId():
            self.drop_down_rocks()
        elif event.timerId() == self.powerup_timer.timerId():
            self.drop_down_powerups()
        elif event.timerId() == self.level_timer.timerId():
            self.game.level_up()
            self.game_level = self.game.level
            if self.game_level == 21:
                self.com.win.emit()
                return
            self.game.set_speed_after_levelup()
            self.main_window.communicate.message_statusbar.\
                emit("Level " + str(self.game_level))
            self.game_timer.start(self.game.game_speed, self)
            self.rock_timer.start(self.game.rock_speed, self)
        elif event.timerId() == self.bullet_timer.timerId():
            if self.bullets.count != 0:
                self.shoot_bullets()

    def powerups_timer_events(self, event):
        """Gets the emitted events from the timers related to the powerups and
        calls the appropriate methods and initializes the appropriate objects
        for each of them.
        """
        if event.timerId() == self.player_invincibility_timer.timerId():
            self.powerup_timer.start(self.game.rock_speed, self)
            self.powerup_ui = PowerupUI(self, self.game, PowerupType.
                                        player_invinciblility)
            self.powerups.append(self.powerup_ui)
        elif event.timerId() == self.big_bomb_timer.timerId():
            self.powerup_timer.start(self.game.rock_speed, self)
            self.powerup_ui = PowerupUI(self, self.game, PowerupType.big_bomb)
            self.powerups.append(self.powerup_ui)
        elif event.timerId() == self.slow_down_rocks_timer.timerId():
            self.powerup_timer.start(self.game.rock_speed, self)
            self.powerup_ui = PowerupUI(self, self.game,
                                        PowerupType.slow_down_rocks)
            self.powerups.append(self.powerup_ui)
        elif event.timerId() == self.shoot_rocks_timer.timerId():
            self.powerup_timer.start(self.game.rock_speed, self)
            self.powerup_ui = PowerupUI(self, self.game,
                                        PowerupType.shoot_rocks)
            self.powerups.append(self.powerup_ui)

    def win_the_game(self):
        """Wins the game and shows an appropriate message to the player."""
        self.game.win()
        self.stop_timers()
        self.main_window.communicate.message_statusbar.\
            emit("You've won the game. You are a survivor. Well done!")

    def drop_down_powerups(self):
        """Moves the powerups down and check if the move is out of the game
        field. If that is true the powerups are removed from the field.
        """
        temp_powerup = None
        for powerup in self.powerups:
            if(powerup.y >= self.game.dimensions[1] - powerup.height):
                temp_powerup = powerup
            else:
                powerup.drop_down()
            self.check_collision_between_player_and_powerup(powerup)
        if temp_powerup is not None:
            self.remove_powerup_from_field(temp_powerup)

    def check_collision_between_player_and_powerup(self, powerup):
        """Checks for a collision between the player and the powerups. If that
        is true initializes the powerups' effect according to their type.
        """
        if(self.game.collision_detected(self.player_ui, powerup)):
            if powerup.type == PowerupType.player_invinciblility:
                self.init_player_invincibility(powerup)
            elif powerup.type == PowerupType.big_bomb:
                self.init_big_bomb()
            elif powerup.type == PowerupType.slow_down_rocks:
                self.init_slow_down_rocks(powerup)
            elif powerup.type == PowerupType.shoot_rocks:
                self.init_shoot_rocks(powerup)

    def init_slow_down_rocks(self, powerup):
        """Initializes the powerup slow_down_rocks and it's effect of the
        game."""
        self.game.set_rock_speed(self.game.rock_speed + 3)
        self.game.set_speed(self.game.game_speed + 25)
        self.game_timer.start(self.game.game_speed, self)
        self.rock_timer.start(self.game.rock_speed, self)
        self.ticker = {"type": "slow_down_rocks",
                       "value": powerup.duration // 1000}

        self.show_slow_down_rocks_info(self.ticker["value"])
        self.ticker_timer.start(PowerupTimeInterval.second, self)
        self.powerup_duration_timer.setSingleShot(True)
        self.powerup_duration_timer.singleShot(powerup.duration,
                                               self.stop_slow_down_rocks)

    def show_slow_down_rocks_info(self, value):
        """Shows information about the powerup slow_down_rocks to the
        player.
        """
        self.main_window.communicate.message_statusbar.\
            emit("The rock are slowed down for " + str(value) + " seconds")

    def stop_slow_down_rocks(self):
        """Stops the effect of the powerup slow_down_rocks and shows a message
        to the player.
        """
        self.powerup_duration_timer.stop()
        self.ticker_timer.stop()
        self.game.set_rock_speed(self.game.rock_speed - 3)
        self.game.set_speed(self.game.game_speed - 25)
        self.game_timer.start(self.game.game_speed, self)
        self.rock_timer.start(self.game.rock_speed, self)
        self.main_window.communicate.message_statusbar.\
            emit("The rock are no longer slowed down. Be careful!")

    def shoot_bullets(self):
        """Moves the bullets up (to the target) and check if the move is out of
        the game field. If that is true the bullets are removed from the field.
        """
        temp_bullet = None
        for bullet in self.bullets:
            if(bullet.y <= 1):
                temp_bullet = bullet
            else:
                bullet.move_to_target()
                self.check_collision_between_bullet_and_rock(bullet)
        if temp_bullet is not None:
            self.remove_bullet_from_field(temp_bullet)

    def check_collision_between_bullet_and_rock(self, bullet):
        """Checks for a collision between the bullets and the rocks. If that
        is true removes the rocks from the game field.
        """
        for rock in self.rocks:
            if self.game.collision_detected(bullet, rock):
                self.remove_rock_from_field(rock)

    def init_shoot_rocks(self, powerup):
        """Initializes the powerup shoot_rocks and it's effect of the game."""
        self.ticker = {"type": "shoot_rocks",
                       "value": powerup.duration // 1000}
        self.show_shoot_rocks_info(self.ticker["value"])
        self.ticker_timer.start(PowerupTimeInterval.second, self)
        self.powerup_duration_timer.setSingleShot(True)
        self.powerup_duration_timer.singleShot(powerup.duration,
                                               self.stop_shoot_rocks)

    def show_shoot_rocks_info(self, value):
        """Shows information about the powerup shoot_rocks to the player."""
        self.main_window.communicate.message_statusbar.\
            emit("You have bullets for " + str(value) + " seconds")

    def stop_shoot_rocks(self):
        """Stops the effect of the powerup shoot_rocks and shows a message
        to the player.
        """
        self.powerup_duration_timer.stop()
        self.ticker_timer.stop()
        self.main_window.communicate.message_statusbar.\
            emit("No more bullets!")

    def init_big_bomb(self):
        """Initializes the powerup big_bomb and it's effect of the game."""
        temp_rocks = self.rocks[:]
        for temp_rock in temp_rocks:
            self.remove_rock_from_field(temp_rock)
        self.main_window.communicate.message_statusbar.\
            emit("BOOM! The blast totally destroyed everything on the field!")

    def init_player_invincibility(self, powerup):
        """Initializes the powerup player_invincibility and it's effect
        of the game.
        """
        if not self.player_ui.is_player_invincible:
            self.player_ui.set_player_invinciblity()
            self.ticker = {"type": "player_invincibility",
                           "value": powerup.duration // 1000}
            self.show_player_invincibility_info(self.ticker["value"])
            self.ticker_timer.start(PowerupTimeInterval.second, self)
            self.powerup_duration_timer.setSingleShot(True)
            self.powerup_duration_timer.singleShot(
                powerup.duration, self.stop_player_invincibility
            )

    def stop_player_invincibility(self):
        """Stops the effect of the powerup player_invincibility and shows a
        message to the player.
        """
        self.powerup_duration_timer.stop()
        self.ticker_timer.stop()
        self.player_ui.set_player_invinciblity()
        self.main_window.communicate.message_statusbar.\
            emit("The player's invinciblility is off. You are mortal again!")

    def show_player_invincibility_info(self, value):
        """Shows information about the powerup player_invincibility_info to the
        player.
        """
        self.main_window.communicate.message_statusbar.\
            emit("The player is invincible for " + str(value) + " seconds")

    def remove_powerup_from_field(self, powerup):
        """Removes a powerup from the game field."""
        self.powerups.remove(powerup)
        powerup.remove_shape()
        if(self.powerups.count == 0):
            self.powerup_timer.stop()

    def remove_bullet_from_field(self, bullet):
        """Removes a bullet from the game field."""
        self.bullets.remove(bullet)
        bullet.remove_shape()
        if(self.bullets.count == 0):
            self.bullet_timer.stop()

    def remove_rock_from_field(self, rock):
        """Removes a rock from the game field."""
        self.rocks.remove(rock)
        rock.remove_shape()

    def drop_down_rocks(self):
        """Moves the rocks down and check if the move is out of the game
        field. If that is true the rocks are removed from the field.
        """
        temp_rock = None
        for rock in self.rocks:
            if(rock.y >= self.game.dimensions[1] - rock.height - 15):
                temp_rock = rock
            else:
                rock.drop_down()
            self.check_collision_between_rock_and_player(rock)
        if temp_rock is not None:
            self.remove_rock_from_field(temp_rock)

    def check_collision_between_rock_and_player(self, rock):
        """Checks for a collision between the rock and the player. If that is
        true the game is over.
        """
        if(not self.player_ui.is_player_invincible and
           self.game.collision_detected(self.player_ui, rock)):
            self.stop_timers()
            self.game.lose()
            self.main_window.communicate.message_statusbar.\
                emit("Game Over")

    def keyPressEvent(self, event):
        """Gets the events emitted when the player presses a key on the
        keyboard and calls the appropriate method.
        """
        super(FieldUI, self).keyPressEvent(event)
        key = event.key()
        if key == Qt.Key_Escape:
            self.com.exit.emit()
        elif key == Qt.Key_R:
            self.com.restart.emit()
        elif self.game.is_lost:
            return
        elif key == Qt.Key_P:
            if self.game.is_running:
                self.pause_game()
            else:
                self.resume_game()
            return
        if self.game.is_paused:
            return
        elif key == Qt.Key_Left:
            self.com.move_left.emit()
        elif key == Qt.Key_Right:
            self.com.move_right.emit()

    def pause_game(self):
        """Pauses the game and shows a message to the player."""
        if self.game.is_running:
            self.game.pause()
            self.stop_timers()
            self.main_window.communicate.message_statusbar.emit("Paused")

    def resume_game(self):
        """Resumes the game and shows a message to the player."""
        if self.game.is_paused:
            self.game.resume()
            self.start_timers()
            self.main_window.communicate.message_statusbar.emit("Running")
        self.update()
예제 #37
0
class CheckCreds(QDialog):
    """
        This class manages the authentication process for oVirt. If credentials are saved, they're
        tried automatically. If they are wrong, the username/password dialog is shown.
    """

    def __init__(self, parent, username, password, remember):
        QDialog.__init__(self, parent)
        self.uname = username
        self.pw = password
        self.remember = False if conf.CONFIG['allow_remember'] == '0' else remember
        self.setModal(True)

        self.initUI()

    def initUI(self):
        """
            Description: A progress bar, a status message will be shown and a timer() method will
                         be invoked as part of the authentication process.
            Arguments: None
            Returns: Nothing
        """

        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)
        
        self.status = QLabel(self)
        self.status.setGeometry(30, 75, 200, 20)

        self.timer = QBasicTimer()
        self.step = 0
        
        self.setGeometry(300, 300, 255, 100)
        self.center()
        self.setWindowTitle(_('loading'))
        self.show()

        self.timer.start(100, self)
    
    def timerEvent(self, e):
        """
            Description: Called periodically as part of the QBasicTimer() object.
                         Authentication will be handled within this method.
            Arguments: The event. Won't be used, though.
            Returns: Nothing, just exits when progress bar reaches 100%
        """

        global conf

        err = QMessageBox()
        self.status.setText(_('authenticating'))

        if not conf.USERNAME:
            try:
                kvm = API(url=conf.CONFIG['ovirturl'], username=self.uname + '@' + conf.CONFIG['ovirtdomain'], password=self.pw, insecure=True, timeout=int(conf.CONFIG['conntimeout']), filter=True)
                conf.OVIRTCONN = kvm
                conf.USERNAME = self.uname
                conf.PASSWORD = self.pw
                self.status.setText(_('authenticated_and_storing'))
                self.step = 49
            except ConnectionError as e:
                err.critical(self, _('apptitle') + ': ' + _('error'), _('ovirt_connection_error') + ': ' + sub('<[^<]+?>', '', str(e)))
                self.status.setText(_('error_while_authenticating'))
                self.step = 100
            except RequestError as e:
                err.critical(self, _('apptitle') + ': ' + _('error'), _('ovirt_request_error') + ': ' + sub('<[^<]+?>', '', str(e)))
                self.status.setText(_('error_while_authenticating'))
                self.step = 100
        
        if self.step >= 100:
            # Authenticacion process has concluded
            self.timer.stop()
            self.close()
            return
        elif self.step == 50:
            # Credentials were ok, we check whether we should store them for further uses
            if self.remember:
                self.status.setText(_('storing_credentials'))
                with os.fdopen(os.open(conf.USERCREDSFILE, os.O_WRONLY | os.O_CREAT, 0600), 'w') as handle:
                    handle.write('[credentials]\nusername=%s\npassword=%s' % (self.uname, encode(self.pw, 'rot_13')))
                    handle.close()
                self.step = 99
            else:
                self.status.setText(_('successfully_authenticated'))
                self.step = 99
            
        self.step = self.step + 1
        self.pbar.setValue(self.step)
예제 #38
0
class EngineWidget(QWidget):
    pvChanged = pyqtSignal(list)

    def __init__(self, parent):
        super().__init__(parent)
        self.board = None
        self.command = None
        self.longestPV = []
        self.lastlongestPV = []
        self.initUI()
        self.timer = QBasicTimer()
        self.timer.start(100, self)

    def initUI(self):
        self.pvLabel = PVLabel(self)
        self.scoreLabel = ScoreLabel(self)
        self.depthLabel = DepthLabel(self)
        self.analyzeButton = AnalyzeButton(self, self.analyzeClicked)

        horiLayout = QHBoxLayout()
        horiLayout.setSpacing(0)
        horiLayout.addWidget(self.scoreLabel)
        horiLayout.addWidget(self.depthLabel, 0, Qt.AlignRight)

        vertiLayout = QVBoxLayout(self)
        vertiLayout.addLayout(horiLayout)
        vertiLayout.addWidget(self.pvLabel)
        vertiLayout.addWidget(self.analyzeButton)

    def initEngine(self, board):
        eng = userConfig.config['ENGINES']['mainEngine']
        engPath = eng + '/' +\
            userConfig.config[eng][str(platform.architecture()[0])]
        print(constants.ENGINES_PATH + '/' + engPath)
        self.engine = chess.uci.popen_engine(constants.ENGINES_PATH + '/' +
                                             engPath)
        self.infoHandler = EngineInfoHandler(self)
        self.infoHandler.newInfo.connect(self.newInfoRecieved)
        self.engine.info_handlers.append(self.infoHandler)
        self.board = copy.deepcopy(board)
        self.engine.uci()
        self.engine.isready(self.stopAndSync)

    def goInfinite(self, stuff=None):
        print('engine infinite thinking')
        self.command = self.engine.go(infinite=True, async_callback=True)

    def startEngineActions(self):
        if self.analyzeButton.isChecked():
            assert self.command is None
            self.engine.isready(self.goInfinite)
        # TODO: Add timed engine

    def stopEngine(self, callback=None):
        print('engine stopping')
        self.engine.stop(callback)
        self.command = None

    def analyzeClicked(self):
        if self.analyzeButton.isChecked():
            self.readyAndGo()
        else:
            self.stopEngine(None)

    # TODO: prettier way for these callbacks?
    def positionAndGo(self, stuff=None):
        print('engine syncing position', self.board.fen())
        if self.board.fen() == chess.STARTING_FEN:
            self.engine.ucinewgame()
        self.engine.position(self.board)
        self.startEngineActions()

    def readyAndGo(self, stuff=None):
        self.engine.isready(self.positionAndGo)

    def stopAndSync(self, stuff=None):
        self.stopEngine(self.readyAndGo)

    def updateAfterMove(self, newNode):
        self.board = copy.deepcopy(newNode.board())
        move = self.board.move_stack[-1]
        if self.longestPV and self.longestPV[0] == move:
            self.longestPV = self.longestPV[1:]
        else:
            self.longestPV.clear()
        if self.analyzeButton.isChecked():
            self.stopAndSync()

    def createScoreText(self, scoreInfo):
        if scoreInfo[1].mate is not None:
            scoreTxt = 'M' + str(scoreInfo[1].mate)
        else:
            scoreTxt = '{:+4.2f}'.format(scoreInfo[1].cp / 100.0)

            conf = userConfig.config['ENGINES']
            if (not self.board.turn and
                    conf.getboolean('showWhiteCentipawns')):
                if scoreTxt[0] == '-':
                    scoreTxt = '+' + scoreTxt[1:]
                else:
                    scoreTxt = '-' + scoreTxt[1:]
        return scoreTxt

    def createPVText(self, isStale):
        if isStale:
            pvTxt = '[Off]'
        else:
            try:
                pvTxt = self.board.variation_san(self.longestPV)
            except ValueError:
                pvTxt = 'Invalid variation_san'
        return pvTxt

    def createText(self):
        pvTxt = 'not thinking'
        scoreTxt = '0'
        depthTxt = '0'
        with self.infoHandler:
            stale = not self.analyzeButton.isChecked()
            if not stale and 1 in self.infoHandler.info['score']:
                scoreTxt = self.createScoreText(self.infoHandler.info['score'])

            if 1 in self.infoHandler.info['pv']:
                pvTxt = self.createPVText(stale)
            if not stale and 'depth' in self.infoHandler.info.keys():
                depthTxt = str(self.infoHandler.info['depth'])

        self.scoreLabel.setText(scoreTxt)
        self.pvLabel.setText(pvTxt)
        self.depthLabel.setText(depthTxt)

    def createBoardSceneGraphics(self):
        if self.longestPV != self.lastlongestPV:
            self.pvChanged.emit(self.longestPV)

    # newInfoRecieved can be called so many times in a row right after
    # an engine receives a new position that the thread locks up.
    def timerEvent(self, event):
        if self.longestPV != self.lastlongestPV:
            self.createText()
            self.createBoardSceneGraphics()
            self.lastlongestPV = copy.deepcopy(self.longestPV)

    def newInfoRecieved(self):
        with self.infoHandler:
            pvInfo = self.infoHandler.info['pv']
            if 1 in pvInfo:
                if (not self.longestPV or pvInfo[1][0] != self.longestPV[0]):
                    self.longestPV = pvInfo[1]
                elif len(pvInfo[1]) > len(self.longestPV):
                    self.longestPV = pvInfo[1]

    def reset(self, newNode, turnOffEngine=False):
        self.board = copy.deepcopy(newNode.board())
        self.longestPV = []
        self.lastlongestPV = []
        self.createText()
        if turnOffEngine:
            self.analyzeButton.setChecked(False)
        else:
            self.stopAndSync()

    def destroyEvent(self):
        print('closing engine')
        self.engine.quit()
예제 #39
0
class GameBoard(QMainWindow):  # 可视化类,pyqt5进行编写。
    def __init__(self):
        print('初始化地图...')
        self.Map = []
        for i in range(config.HEIGHT):
            col = []
            for j in range(config.WIDTH):
                col.append(0)
            self.Map.append(col)
        self.startPoint = None
        self.endPoint = None
        self.search = None
        self.centerTimer = None
        self.yi = None
        self.special = None
        self.displayFlush = False
        super().__init__()
        print('初始化UI...')
        self.initUI()

    def initUI(self):
        # 开始初始化UI部分
        # 创建UI控件
        self.label_tips = QLabel(
            "<p style='color:green'>使用说明:</p>右键单击格子选定起始点,左键格子选定格子为墙壁或删除墙壁。\n<p style='color:green'>颜色说明:</p>\n黄色代表起点,绿色代表终点,黑色代表墙壁,红色代表待搜索的open列表,灰色代表已搜索过的close列表,蓝色代表当前搜索到的路径",
            self)
        self.label_display = QLabel("", self)
        self.button_start = QPushButton("开始搜索", self)
        self.button_clearSE = QPushButton("重选起始点", self)
        self.button_clearWall = QPushButton("清空地图墙壁", self)
        self.button_saveMap = QPushButton("保存地图", self)
        self.button_loadMap = QPushButton("加载地图", self)

        # 设置控件属性
        self.label_tips.setWordWrap(True)
        self.label_display.setWordWrap(True)
        # 设置控件样式
        self.label_display.setStyleSheet("border:1px solid black")
        self.label_display.setAlignment(Qt.AlignLeft)
        self.label_display.setAlignment(Qt.AlignTop)
        # 设置控件的尺寸和位置
        self.label_tips.resize(200, 150)
        self.button_saveMap.resize(80, 30)
        self.button_loadMap.resize(80, 30)
        self.label_display.resize(200, 300)

        self.label_tips.move(100 + (config.WIDTH - 1) * config.blockLength, 0)
        self.label_display.move(100 + (config.WIDTH - 1) * config.blockLength,
                                400)
        self.button_start.move(100 + (config.WIDTH - 1) * config.blockLength,
                               200)
        self.button_clearSE.move(100 + (config.WIDTH - 1) * config.blockLength,
                                 250)
        self.button_clearWall.move(
            100 + (config.WIDTH - 1) * config.blockLength, 300)
        self.button_saveMap.move(100 + (config.WIDTH - 1) * config.blockLength,
                                 350)
        self.button_loadMap.move(200 + (config.WIDTH - 1) * config.blockLength,
                                 350)
        # 给控件绑定事件
        self.button_start.clicked.connect(self.button_StartEvent)
        self.button_clearSE.clicked.connect(self.button_Clear)
        self.button_clearWall.clicked.connect(self.button_Clear)
        self.button_saveMap.clicked.connect(self.button_SaveMap)
        self.button_loadMap.clicked.connect(self.button_LoadMap)
        # UI初始化完成
        self.setGeometry(
            0, 0, 150 +
            (config.WIDTH * config.blockLength - config.blockLength) + 200,
            150 + (config.HEIGHT * config.blockLength - config.blockLength))
        self.setMinimumSize(
            150 + (config.WIDTH * config.blockLength - config.blockLength) +
            200,
            150 + (config.HEIGHT * config.blockLength - config.blockLength))
        self.setMaximumSize(
            150 + (config.WIDTH * config.blockLength - config.blockLength) +
            200,
            150 + (config.HEIGHT * config.blockLength - config.blockLength))
        self.setWindowTitle('A*搜索')
        self.show()

    def addDisplayText(self, text):
        if self.displayFlush:
            self.label_display.setText(text + '\n')
            self.displayFlush = False
        else:
            self.label_display.setText(self.label_display.text() + text + '\n')

    def mousePressEvent(self, event):
        x, y = event.x() - 50, event.y() - 50
        x = x // config.blockLength
        y = y // config.blockLength
        if x >= 0 and x < config.WIDTH and y >= 0 and y < config.HEIGHT:
            if event.button() == Qt.LeftButton:
                if (x, y) != self.startPoint and (x, y) != self.endPoint:
                    self.Map[y][x] = (1 if self.Map[y][x] == 0 else 0)
            if event.button() == Qt.RightButton:
                if self.Map[y][x] == 0:
                    if self.startPoint == None:
                        self.startPoint = (x, y)
                        self.addDisplayText('添加了一个起点:(%d,%d)' % (x, y))
                    elif self.endPoint == None and self.startPoint != (x, y):
                        self.endPoint = (x, y)
                        self.addDisplayText('添加了一个终点:(%d,%d)' % (x, y))
            self.repaint()

    def button_StartEvent(self):
        sender = self.sender()
        print(sender)
        if self.startPoint != None and self.endPoint != None:
            if self.centerTimer == None:
                self.centerTimer = QBasicTimer()
            self.button_start.setEnabled(False)
            self.button_clearSE.setEnabled(False)
            self.button_clearWall.setEnabled(False)
            self.centerTimer.start(200, self)
            self.search = A_Search(
                point(self.startPoint[1], self.startPoint[0]),
                point(self.endPoint[1], self.endPoint[0]), self.Map)
            self.yi = self.search.process()
            self.addDisplayText('开始进行搜索')

    def button_SaveMap(self):
        with open('map.txt', 'w') as f:
            f.write(json.dumps(self.Map))
            self.addDisplayText('地图保存成功-->map.txt')

    # else:
    # self.addDisplayText('地图保存失败')
    def button_LoadMap(self):
        try:
            with open('map.txt', 'r') as f:
                self.Map = json.loads(f.read())
                config.HEIGHT = len(self.Map)
                config.WIDTH = len(self.Map[0])
                self.addDisplayText('地图加载成功')
                self.repaint()
        except Exception as e:
            print('失败', e, type(e))
            if type(e) == FileNotFoundError:
                self.addDisplayText('地图加载失败:地图文件不存在')
            elif type(e) == json.decoder.JSONDecodeError:
                self.addDisplayText('地图加载失败:错误的地图文件')

    def button_Clear(self):
        sender = self.sender()
        print(self.button_clearSE, type(self.button_clearSE))
        if sender == self.button_clearSE:
            self.startPoint = None
            self.endPoint = None
            self.repaint()
            self.addDisplayText('清空起始点')
        elif sender == self.button_clearWall:
            for i in range(len(self.Map)):
                for j in range(len(self.Map[i])):
                    self.Map[i][j] = 0
            self.repaint()
            self.addDisplayText('清空所有墙壁')

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        self.drawBoard(event, qp)
        qp.end()

    def drawBoard(self, event, qp):
        self.drawMap(qp)

    def drawMap(self, qp):  # 画面绘制方法,每次地图有所改动都将重绘
        time1 = time.time()
        if self.search != None:
            if self.special != None:
                e = self.special[0]
                path = [e]
                while True:
                    e = e.father
                    if e != None:
                        path.append(e)
                    else:
                        break
            else:
                path = None
            pen = QPen(QColor(0, 0, 0), 1, Qt.SolidLine)
            qp.setPen(pen)
            for i in range(len(self.Map)):
                for j in range(len(self.Map[i])):
                    wordTag = False
                    if i == self.search.start.x and j == self.search.start.y:
                        qp.setBrush(QColor(255, 255, 0))
                    elif i == self.search.end.x and j == self.search.end.y:
                        qp.setBrush(QColor(100, 200, 50))
                    else:
                        if self.Map[i][j] == 0:
                            tagx = True
                            if path:
                                for k in path:
                                    if k.x == i and k.y == j:
                                        tagx = False
                                        qp.setBrush(QColor(0, 100, 255))
                            if tagx:
                                if self.special != None:
                                    if i == self.special[
                                            0].x and j == self.special[0].y:
                                        qp.setBrush(QColor(0, 255, 0))
                                    else:
                                        tag = True
                                        for k in self.special[1]:
                                            if k.x == i and k.y == j:
                                                tag = False
                                                wordTag = True
                                                word = str(k.F)

                                                qp.setBrush(QColor(150, 0, 0))
                                                break
                                            else:
                                                qp.setBrush(
                                                    QColor(220, 220, 220))
                                        if tag:
                                            for k in self.special[2]:
                                                if k.x == i and k.y == j:
                                                    qp.setBrush(
                                                        QColor(150, 150, 150))
                                                    break
                                                else:
                                                    qp.setBrush(
                                                        QColor(220, 220, 220))
                                else:
                                    qp.setBrush(QColor(220, 220, 220))
                        elif self.Map[i][j] == 1:
                            qp.setBrush(QColor(0, 0, 0))
                        else:
                            qp.setBrush(QColor(255, 0, 0))
                    qp.drawRect(50 + j * config.blockLength,
                                50 + i * config.blockLength,
                                config.blockLength, config.blockLength)
                    if wordTag:
                        qp.setFont(QFont('楷体', 5, QFont.Light))
                        qp.drawText(50 + 10 + j * config.blockLength,
                                    50 + 10 + i * config.blockLength, word)
                        wordTag = False
        # time.sleep(20)
        else:
            for i in range(len(self.Map)):
                for j in range(len(self.Map[i])):
                    if (j, i) == self.startPoint:
                        qp.setBrush(QColor(255, 255, 0))
                    elif (j, i) == self.endPoint:
                        qp.setBrush(QColor(100, 200, 50))
                    else:
                        if self.Map[i][j] == 0:
                            qp.setBrush(QColor(220, 220, 220))
                        elif self.Map[i][j] == 1:
                            qp.setBrush(QColor(0, 0, 0))
                        else:
                            qp.setBrush(QColor(255, 0, 0))

                    qp.drawRect(50 + j * config.blockLength,
                                50 + i * config.blockLength,
                                config.blockLength, config.blockLength)
        time2 = time.time()

    # time.sleep(20)
    # print('绘制时间:',time2-time1)
    def timerEvent(self, e):
        try:
            data = next(self.yi)
        except Exception as e:
            self.addDisplayText('搜索结束:')
            print('搜索结束!')
            if self.search.result == None:
                self.addDisplayText('未找到可行路径')
                print('搜索结束!')
            else:
                self.addDisplayText('总计搜索节点数:%d' % self.search.count)
                self.addDisplayText('最终路径长度:%d' % len(self.search.result))
            self.centerTimer.stop()
            self.search = None
            self.yi = None
            self.special = None
            point.clear()
            self.button_start.setEnabled(True)
            self.button_clearSE.setEnabled(True)
            self.button_clearWall.setEnabled(True)
            self.displayFlush = True
        else:
            self.special = data
            self.repaint()
예제 #40
0
class Board(QFrame):  # класс где пишется игровая логика
    msg2Statusbar = pyqtSignal(
        str
    )  # сигнал, который срабатывает, когда мы хотим написать сообщение в строку состояния
    BoardWidth = 10  # переменная определ ширину в блоках
    BoardHeight = 22  # переменная определ высоту в блоках
    Speed = 300  # скорость игры, каждые 300мс будет начинаться цикл новой игры

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

    def initBoard(self):
        self.timer = QBasicTimer()
        self.isWaitingAfterLine = False
        self.curX = 0
        self.curY = 0
        self.numLinesRemoved = 1
        self.board = [
        ]  # список чисел от 0 до 7, представляет местоположение фигур и оставляет фигуры на доске
        self.setFocusPolicy(Qt.StrongFocus)
        self.isStarted = False
        self.isPaused = False
        self.clearBoard()

    def shapeAt(self, x, y):  # определяет тип фигуры в данном блоке
        return self.board[(y * Board.BoardWidth) + x]

    def setShapeAt(self, x, y, shape):
        self.board[(y * Board.BoardWidth) + x] = shape

    def squareWidth(self):  # ширина простого квадратика в пикселях
        return self.contentsRect().width() // Board.BoardWidth

    def squareHeight(self):  # высота простого квадратика в пикселях
        return self.contentsRect().height() // Board.BoardHeight

    def start(self):
        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):
        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):
        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):
        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):
        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):
        for i in range(Board.BoardHeight * Board.BoardWidth):
            self.board.append(Tetrominoe.NoShape)

    def dropDown(self):
        newY = self.curY
        while newY > 0:
            if not self.tryMove(self.curPiece, self.curX, newY - 1):
                break
            newY -= 1
        self.pieceDropped()

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

    def pieceDropped(self):
        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):
        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):
        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):
        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):
        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)
예제 #41
0
class OpenGLWidget(QOpenGLWidget):

    def __init__(self, *args, **kwargs):
        '''
        Class representing OpenGL widget in the VisualizationWindow.
        '''
        super(OpenGLWidget, self).__init__(*args, **kwargs)
        self._room = self.parent().room   # assign room geometry to a variable
        self.setGeometry(self.parent()._width * .25, 0, self.parent()._width, self.parent()._height)   # window size/pos
        self._timer = QBasicTimer()   # create a timer

    def initializeGL(self):
        '''
        A method to initialize all OpenGL features.
        '''
        glClearColor(.22, .22, .22, 1)   # set background color to gray
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)   # make sure to clear everything at the beginning
        glClearDepth(1)   # set background depth to farthest
        glEnable(GL_DEPTH_TEST)   # enable depth testing for z-culling
        glDepthFunc(GL_LEQUAL)   # set the type of depth-test
        glShadeModel(GL_SMOOTH)   # enable smooth shading
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)   # nice perspective corrections
        glMatrixMode(GL_PROJECTION)   # necessary for a nice perspective view
        glLoadIdentity()   # necessary for a nice perspective view
        gluPerspective(45, (self.width() / self.height()), .1, 50.0)   # configure perspective view
        glMatrixMode(GL_MODELVIEW)   # necessary for a nice model view
        glLoadIdentity()   # necessary for a nice model view
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)   # wireframe rendering method
        gluLookAt(   # camera position and looking point
            -15, 8, -15,
            -3, 0, 0,
            0, 1, 0
        )

    def paintGL(self):
        '''
        A method to paint in OpenGL.
        '''
        glClearColor(.22, .22, .22, 1)   # set background color to gray
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)   # clear everything before rendering next frame

        self._draw_grid()   # drawing grid lines
        self._draw_room()   # drawing room geometry

        if self._timer.isActive():   # if animation is initialized
            self._draw_particles()   # draw sound waves represented by particles

    def timerEvent(self, QTimerEvent):
        '''
        An overridden method of what happens on each self._timer tick.
        Warning! This method should only be used by self.initialize_animation()!!
        :param QTimerEvent: should be ignored
        '''
        self.update()   # calling self.update() in order to refresh the widget

    def initialize_animation(self, source_pos=(0,0,0), source_spl=80, source_freq=1000, fps=60):
        '''
        A method to animate the ray tracing method in 4D.
        :param source_pos: source position tuple
        :param source_spl: source sound pressure level
        :param source_freq: source sound frequency
        '''
        self._source_pos = source_pos
        self._source_spl = source_spl
        self._source_power = 10 ** (self._source_spl * .1)
        self._source_freq = source_freq
        self._calculate_particles_normals_positions_energies()
        self._timer.start(1000 / fps, self)

    def _draw_grid(self):
        '''
        A method to draw grid lines.
        '''
        glLineWidth(1)   # width of a single grid line
        glColor3f(.29, .29, .29, 1)   # color of a single grid line (gray)
        glBegin(GL_LINES)   # tell OpenGL to draw lines
        grid_lines = 10   # grid lines range (meaning its gird lines number / 4)
        for i in range(-grid_lines, grid_lines + 1):   # drawing grid lines
            glVertex3f(-grid_lines, 0, i)   # draw a horizontal line
            glVertex3f(grid_lines, 0, i)
            glVertex3f(i, 0, -grid_lines)   # draw a vertical line
            glVertex3f(i, 0, grid_lines)
        glColor3f(.52, .07, .07, 1)   # change line color to red
        glVertex3f(-grid_lines, 0, 0)   # draw red grid line
        glVertex3f(grid_lines, 0, 0)
        glColor3f(.07, .52, .07, 1)   # change line color to green
        glVertex3f(0, 0, -grid_lines)   # draw green grid line
        glVertex3f(0, 0, grid_lines)
        glEnd()   # tell OpenGL to stop drawing

    def _draw_room(self):
        '''
        A method to draw room geometry.
        '''
        faces = self._room.faces   # store room faces in a new variable
        points = self._room.points   # store room points in a new variable
        glColor3f(.59, .59, .62, 1)   # color of an edge (light gray)
        for id in faces:   # iterate through all faces
            glBegin(GL_POLYGON)   # tell OpenGL to draw a polygon
            for point_id in faces[id][:-1]:   # iterate through all points in a single face
                glVertex3fv(points[point_id])   # draw a single point
            glEnd()   # tell OpenGL to stop drawing

    def _draw_particles(self):
        '''
        A method to draw sound waves represented by particles.
        '''
        glBegin(GL_POINTS)   # tell OpenGL to draw points
        for index, particle in enumerate(self._particles_positions):   # iterate through all particles
            green = self._particles_energies[index] / self._source_spl   # computing green color share in rgb palette
            red = 1 - green   # computing red color share in rgb palette
            glColor3f(red, green, 0, 1)   # color of a particle (initially green, then turning red)
            glVertex3f(particle[0], particle[1], particle[2])   # draw each particle
        self._recalculate_particles_normals()   # recalculate particles normals
        self._recalculate_particles_positions()   # recalculate particles positions
        glEnd()   # stop drawing

    def _calculate_particles_normals_positions_energies(self):
        '''
        A method to calculate normal vectors of all particles.
        Warning! This method should be used only after initialize_animation()!
        '''
        particles_count = 15   # not the exact particles count, number of particles in a single ring
        radius = .5   # radius of starting sphere
        self._particles_normals = []   # list of all particles normals
        self._particles_positions = []   # list of all particles current positions
        self._particles_energies = []   # list of all particles energies that reduce each time a particle reflects
        for i in range(0, particles_count):   # iterate through each ring of particles
            for j in range(0, particles_count):   # iterate through each particle in the current ring
                x = cos(2*pi * j / (particles_count-1)) * sin(pi * i / (particles_count-1))   # x position of particle
                y = sin(-pi/2 + pi * i / (particles_count-1))   # y position of particle
                z = sin(2*pi * j / (particles_count-1)) * sin(pi * i / (particles_count-1))   # z position of particle
                self._particles_normals.append([x, y, z])   # add normal vector of each particle to the list
                self._particles_positions.append([x*radius+self._source_pos[0],   # add position of each particle
                                                  y*radius+self._source_pos[1],   # to the list
                                                  z*radius+self._source_pos[2]])
                self._particles_energies.append(self._source_spl)   # each particle has energy equal to source spl

    def _recalculate_particles_normals(self):
        '''
        A method to recalculate all particles normals in each frame.
        Recalculates particles energies within each reflection and removes the particles with energy level below 60dB.
        '''
        self._particles_to_delete = []   # a list with indexes of particles with energy level below 60dB
        for index, particle in enumerate(self._particles_positions):   # iterate through all particles
            if particle[0] <= self._room.boundaries['min_x'] or particle[0] >= self._room.boundaries['max_x']:
                self._compute_new_particle_normal_and_reduce_energy('x', index)   # react to particle reflection
            elif particle[1] <= self._room.boundaries['min_y'] or particle[1] >= self._room.boundaries['max_y']:
                self._compute_new_particle_normal_and_reduce_energy('y', index)   # react to particle reflection
            elif particle[2] <= self._room.boundaries['min_z'] or particle[2] >= self._room.boundaries['max_z']:
                self._compute_new_particle_normal_and_reduce_energy('z', index)   # react to particle reflection
        for particle in sorted(self._particles_to_delete, reverse=True):   # deleting particles with energy below 60dB
            del self._particles_normals[particle]
            del self._particles_positions[particle]
            del self._particles_energies[particle]

    def _recalculate_particles_positions(self):
        '''
        A method to recalculate all particles positions in each frame.
        '''
        for index, particle in enumerate(self._particles_positions):   # iterate through all particles
            normal = self._particles_normals[index]   # assign a particle normal vector to a variable
            self._particles_positions[index] = [   # override previous particle position with a new position
                particle[0]+normal[0]*.1,
                particle[1]+normal[1]*.1,
                particle[2]+normal[2]*.1
            ]

    def _compute_new_particle_normal_and_reduce_energy(self, axis, index):
        '''
        A method to compute new particle normals and reduce its energy level after reflection.
        :param axis: either 'x', 'y' or 'z' based on which axis does the particle reflects
        :param index: index of particle in all global lists
        '''
        normal = self._particles_normals[index]   # assign a particle normal vector to a variable
        if axis == 'x':
            self._particles_normals[index] = ([-normal[0], normal[1], normal[2]])   # reflecting the particle
        elif axis == 'y':
            self._particles_normals[index] = ([normal[0], -normal[1], normal[2]])   # reflecting the particle
        else:
            self._particles_normals[index] = ([normal[0], normal[1], -normal[2]])   # reflecting the particle
        # reducing particle energy
        self._particles_energies[index] = 10 * log10(10 ** (self._particles_energies[index] * .1) * (1 - self._room.average_alpha[self._source_freq]))
        if self._particles_energies[index] < self._source_spl - 60:
            self._particles_to_delete.append(index)   # queueing the particle to removal when its energy is below 60dB
예제 #42
0
class BeatTheSleeper(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.timer = QBasicTimer()
        self.steps = 0

        self.last = 0
        self.scores = 0

        grid = QGridLayout()
        grid.setSpacing(10)

        self.holes = []
        x, y = 0, 0
        for i in range(9):
            self.holes.append(QPushButton("Unactive", self))
            self.holes[i].setIcon(QIcon("hole.png"))
            self.holes[i].setIconSize(QSize(200, 200))

            self.holes[i].clicked.connect(self.doAction)

            grid.addWidget(self.holes[i], x, y)
            if y < 2:
                y += 1
            else:
                x += 1
                y = 0

        self.scores = QLabel("0")
        self.time = QLabel("20")
        self.startButton = QPushButton('Начать')

        grid.addWidget(self.scores, 3, 0)
        grid.addWidget(self.time, 3, 1)
        grid.addWidget(self.startButton, 3, 2)
        self.startButton.clicked.connect(self.startGame)

        self.setLayout(grid)
        self.setGeometry(100, 100, 850, 850)
        self.setWindowTitle('Саид бьет кротов из открытого космоса')
        self.show()

    def startGame(self):
        self.timer.start(500, self)
        self.scores.setText("0")
        self.startButton.setEnabled(False)

    def timerEvent(self, e):
        self.hideSleeper()
        self.jumpSleeper()

        if self.steps >= 40:
            self.timer.stop()
            self.startButton.setEnabled(True)
            self.time.setText("20")
            self.steps = 0
            self.hideSleeper()
            return

        self.steps += 1

        if self.steps % 2 == 0:
            temp_time = int(self.time.text()) - 1
            self.time.setText(str(temp_time))

    def jumpSleeper(self):
        number = randint(0, 8)
        self.holes[number].setIcon(QIcon("sleeper.png"))
        self.holes[number].setText("Active")
        self.last = number

    def hideSleeper(self):
        self.holes[self.last].setIcon(QIcon("hole.png"))
        self.holes[self.last].setText("Unactive")

    def doAction(self):
        sender = self.sender()
        if sender.text() == "Active":
            self.hideSleeper()
            temp_scores = int(self.scores.text()) + 1
            self.scores.setText(str(temp_scores))
예제 #43
0
파일: board_ui.py 프로젝트: tvetan/Reversi
class BoardUi(QFrame):

    def __init__(self, parent, game):
        super().__init__(parent)
        self.main_window = parent
        self.game = game

    def start(self):
        self.show()
        self.setFocusPolicy(Qt.StrongFocus)
        self.timer = QBasicTimer()
        self.timer.start(150, self)
        if isinstance(self.game.first_player, Computer) \
            and isinstance(self.game.second_player, Computer):
            self.computers_play()

    def computers_play(self):
        while not self.game.is_game_won():
            self.computer_turn()
        #self.show_winner_message()

    def init_signals(self):
        self.communicate = Communicate()
        self.communicate.restart.connect(self.restart_game)

    def paintEvent(self, e):
        painter = QPainter()
        painter.begin(self)
        self.draw_board_rectangle(painter)
        painter.end()

    def draw_board_rectangle(self, painter):
        col = QColor(0, 0, 0)
        col.setNamedColor('#d4d4d4')
        painter.setPen(col)

        painter.setBrush(QColor(200, 0, 0))
        painter.drawRect(X_OFFSET, Y_OFFSET, 400, 400)

        pen = QPen(Qt.black, 2, Qt.SolidLine)

        painter.setPen(pen)
        for spot in [(x, x) for x in range(WIDTH + 1)]:
            left = ((spot[0] * SPACE) + X_OFFSET, Y_OFFSET)
            right = ((spot[0] * SPACE) + X_OFFSET, Y_OFFSET + (HEIGHT * SPACE))
            up = (X_OFFSET, (spot[1] * SPACE) + Y_OFFSET)
            down = (X_OFFSET + (WIDTH * SPACE), (spot[1] * SPACE) + Y_OFFSET)
            painter.drawLine(left[0], left[1], right[0], right[1])
            painter.drawLine(up[0], up[1], down[0], down[1])

        for x in range(WIDTH):
            for y in range(HEIGHT):
                centerx, centery = self.get_center(x, y)
                if self.game.board.pieces[x][y].state in PLAYERS_STATES:
                    if self.game.board.pieces[x][y].state == State.white:
                        painter.setBrush(Qt.white)
                    else:
                        painter.setBrush(Qt.black)
                    center = QPoint(centerx, centery)

                    circle_diameter = int(SPACE / 2) - 5
                    painter.drawEllipse(
                        center, circle_diameter, circle_diameter)

    def get_center(self, x, y):
        return X_OFFSET + x * SPACE + int(SPACE / 2), \
            Y_OFFSET + y * SPACE + int(SPACE / 2)

    def timerEvent(self, event):
        self.update()

    def get_clicked_block_position(self, mouseX, mouseY):
        for x in range(WIDTH):
            for y in range(HEIGHT):
                if mouseX > x * SPACE + X_OFFSET and \
                   mouseX < (x + 1) * SPACE + X_OFFSET and \
                   mouseY > y * SPACE + Y_OFFSET and \
                   mouseY < (y + 1) * SPACE + Y_OFFSET:
                    return (x, y)

        return None

    def mousePressEvent(self, event):
        if isinstance(self.game.get_current_player(), Computer):
            return

        position = event.pos()
        piece_position = self.get_clicked_block_position(
            position.x(), position.y())

        if piece_position is None:
            return

        current_player = self.game.get_current_player()
        other_player = self.game.get_other_player()

        is_valid = current_player.make_move(
            piece_position[0], piece_position[1], other_player)

        if not is_valid:
            return

        self.game.change_current_player()

        if self.game.is_game_won():
            self.show_winner_message()
            return

        if isinstance(self.game.get_current_player(), Computer):
            self.computer_turn()

        message = str(
            self.get_current_player_message()
                + " | Scores: " + self.get_score_text())
        self.main_window.communicate.message_statusbar.emit(message)

    def get_current_player_message(self):
        if self.game.first_player.colour == self.game.current_player_colour:
            return "First player's turn with " \
                + self.game.current_player_colour.name

        return "Second player's turn with " \
            + self.game.current_player_colour.name

    def show_winner_message(self):
        winner = self.game.get_winner()
        message = None
        if winner is None:
            message = "No one won its a tie"
        elif winner is self.game.first_player:
            message = "First Player has won"
        else:
            message = "Second Player has won"

        self.main_window.communicate.message_statusbar.emit(message)

    def get_score_text(self):
        text = 'Player 1: %s    Player 2: %s'
        first_player_score = self.game.first_player.score
        second_player_score = self.game.second_player.score

        return text % (first_player_score, second_player_score)

    def restart_game(self):
        self.game.reset_game()
        self.update()
        message = str(
            self.get_current_player_message()
            + " | Scores: " + self.get_score_text())
        self.main_window.communicate.message_statusbar.emit(message)

    def computer_turn(self):
        current_player = self.game.get_current_player()
        other_player = self.game.get_other_player()
        current_player.make_move(other_player)
        self.game.change_current_player()

        if self.game.is_game_won():
            print("here")
            self.show_winner_message()
예제 #44
0
class Board(QFrame):
    BoardWidth = 10
    BoardHeight = 10
    Speed = 300

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

        self.initBoard()

    def initBoard(self):
        self.timer = QBasicTimer()
        self.board = [(Board.BoardWidth // 2, Board.BoardHeight // 2)]
        self.direct = Direct.Left
        self.setFocusPolicy(Qt.StrongFocus)
        self.newFood()

    def start(self):
        self.timer.start(Board.Speed, self)

    def tryMove(self):
        if self.direct == Direct.Right:
            x = self.board[0][0] + 1
            y = self.board[0][1]

        elif self.direct == Direct.Left:
            x = self.board[0][0] - 1
            y = self.board[0][1]

        elif self.direct == Direct.Down:
            x = self.board[0][0]
            y = self.board[0][1] + 1

        elif self.direct == Direct.Up:
            x = self.board[0][0]
            y = self.board[0][1] - 1

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

        if (x, y) in self.board:
            return False

        self.board.insert(0, (x, y))

        if not self.eatFood(x, y):
            self.board.pop()

        self.update()

        return True

    def eatFood(self, x, y):
        if self.food == (x, y):
            self.newFood()
            return True
        else:
            return False

    def newFood(self):
        self.food = (random.randint(0, Board.BoardWidth - 1),
                     random.randint(0, Board.BoardHeight - 1))

        if self.food in self.board:
            self.newFood()

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

        key = event.key()

        if key == Qt.Key_Left:
            if self.direct != Direct.Left and self.direct != Direct.Right:
                self.direct = Direct.Left
                self.tryMove()

        elif key == Qt.Key_Right:
            if self.direct != Direct.Right and self.direct != Direct.Left:
                self.direct = Direct.Right
                self.tryMove()

        elif key == Qt.Key_Down:
            if self.direct != Direct.Down and self.direct != Direct.Up:
                self.direct = Direct.Down
                self.tryMove()

        elif key == Qt.Key_Up:
            if self.direct != Direct.Up and self.direct != Direct.Down:
                self.direct = Direct.Up
                self.tryMove()

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

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

        painter = QPainter(self)

        for i in range(len(self.board)):
            x = self.board[i][0]
            y = self.board[i][1]
            color = 2
            if i == 0:
                color = 3
                self.drawEllipse(painter, x * self.squareWidth(),
                                 y * self.squareHeight(), color)
                continue
            self.drawSquare(painter, x * self.squareWidth(),
                            y * self.squareHeight(), color)

        self.drawSquare(painter, self.food[0] * self.squareWidth(),
                        self.food[1] * self.squareHeight(), 5)

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

        if event.timerId() == self.timer.timerId():
            self.tryMove()
        else:
            super(Board, self).timerEvent(event)

    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
        # return self.squareWidth()

    def drawEllipse(self, painter, x, y, color):
        colorTable = [
            0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 0xCCCC66, 0xCC66CC,
            0x66CCCC, 0xDAAA00
        ]
        color = QColor(colorTable[color])
        painter.setBrush(color)
        painter.setPen(color, 0)
        painter.drawEllipse(x, y, self.squareWidth(), self.squareHeight())

    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)
예제 #45
0
파일: main.py 프로젝트: Xevaquor/aipac
class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

        self.keyboard_state = {'North' : False, 'South' : False, 'West' : False, 'East' : False, 'Stop' : False}

        self.agents = [HumanAgent(0), StopAgent(1)]
        self.layout = Layout()
        self.layout.load_from_file("test.lay")
        self.colors = {Tile.Empty: QBrush(QColor(26,26,26)),
                       Tile.Wall: QBrush(QColor(12,12,225)),
                       Tile.Start: QBrush(QColor(255,255,0))}

        self.game = PacmanGame(self.layout)
        self.current_game_state = self.game.get_initial_game_state()

        self.timer = QBasicTimer()

        self.timer.start(500, self)

    def timerEvent(self, event):

        for i in range(2):
            agent = self.agents[i]
            move = agent.make_decision(self.current_game_state, self.game, self.keyboard_state)
            assert move in self.game.get_legal_moves(self.current_game_state)
            self.current_game_state = self.game.apply_move(self.current_game_state, move, i)


        #move = self.pacman_agent.make_decision(self.current_game_state, self.game, self.keyboard_state)

        # assert that returned move is valid

        #self.current_game_state = self.game.apply_move(self.current_game_state, move, 0)

        self.repaint()

    def initUI(self):
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Draw text')
        self.show()

    def keyPressEvent(self, event: QKeyEvent):
        if event.key() == 0x01000013:
            self.keyboard_state['North'] = True
        elif event.key() == 0x01000015:
            self.keyboard_state['South'] = True
        elif event.key() == 0x01000012:
            self.keyboard_state['West'] = True
        elif event.key() == 0x01000014:
            self.keyboard_state['East'] = True

    def keyReleaseEvent(self, event : QKeyEvent):
        if event.key() == 0x01000013:
            self.keyboard_state['North'] = False
        elif event.key() == 0x01000015:
            self.keyboard_state['South'] = False
        elif event.key() == 0x01000012:
            self.keyboard_state['West'] = False
        elif event.key() == 0x01000014:
            self.keyboard_state['East'] = False


    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        qp.setPen (QPen(QColor(0,0,0,0)))
        ysize, xsize = self.layout.shape
        canvas = self.contentsRect()
        for y in range(ysize):
            for x in range(xsize):
                qp.setBrush(self.colors[self.layout.grid[y][x]])
                qp.drawRect(TILE_SIZE * x, TILE_SIZE * y, TILE_SIZE, TILE_SIZE)
                #Color(rgb=self.colors[self.layout.grid[y][x]])
                #Rectangle(pos=(TILE_SIZE * x, TILE_SIZE * y), size=(TILE_SIZE, TILE_SIZE))

        pac_x = self.current_game_state.agents[0].position[0] * TILE_SIZE
        pac_y = self.current_game_state.agents[0].position[1] * TILE_SIZE
        qp.setBrush(QBrush(QColor(255,255,0)))
        qp.drawEllipse(pac_x, pac_y, TILE_SIZE, TILE_SIZE)

        for g in self.current_game_state.agents[1:]:
            g_x = g.position[0] * TILE_SIZE
            g_y = g.position[1] * TILE_SIZE
            qp.setBrush(QBrush(QColor(255,0,0)))
            qp.drawEllipse(g_x, g_y, TILE_SIZE, TILE_SIZE)

        for y in range(ysize):
            for x in range(xsize):
                if self.current_game_state.food[y][x]:
                    qp.setBrush(QBrush(QColor(255,255,255)))
                    qp.drawEllipse(x * TILE_SIZE + TILE_SIZE / 2,
                                 y * TILE_SIZE + TILE_SIZE / 2,
                            TILE_SIZE / 4, TILE_SIZE / 4)

        qp.end()


    def drawText(self, event, qp):
        qp.setPen(QColor(168, 34, 3))
        qp.setFont(QFont('Decorative', 10))
        qp.drawText(event.rect(), Qt.AlignCenter, self.text)
예제 #46
0
class Board(QFrame):

    msg2Statusbar = pyqtSignal(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)
예제 #47
0
파일: gui.py 프로젝트: sulovm/starsMaze
class Field(QWidget):

    def __init__(self, game):
        super().__init__()
        self.init_field(game)

    def init_field(self, game):
        self.game = game
        self.ways = Ways()
        self.timer = QBasicTimer()
        self.height = self.game.field.get_height()
        self.width = self.game.field.get_width()
        self.mat = self.game.field
        grid = QGridLayout()
        self.setLayout(grid)
        grid.setSpacing(1)
        self.draw()
        self.timer.start(600, self)

    def draw(self):
        """Draws the game field each time a change occurs."""
        grid = self.layout()
        width, height = self.width, self.height
        mat = self.game.field.mat

        for i in range(height):
            for j in range(width):
                tile = Tile(str(mat[i][j]))
                tile.setStyle(mat[i][j])
                grid.addWidget(tile, i, j)

        label1 = QLabel('Health: {} Energy: {} Stars: {}'.format(
            self.game.player.get_health(),
            self.game.player.get_energy(),
            self.game.player.get_stars()))
        grid.addWidget(label1, height, 0, 1, width - 1)
        label2 = QLabel('>>')
        label2.setStyleSheet("qproperty-alignment: AlignRight;")
        grid.addWidget(label2, height, width - 1, 1, width)
        if (self.game.state is not State.running):
            lev_num = ''
        else:
            lev_num = str(self.game.level)
        label3 = QLabel('{}{}'.format(self.game.state.value, lev_num))
        grid.addWidget(label3, height + 1, 0, 1, width)

    def clear(self):
        """Removes all widgets before each drawing."""
        grid = self.layout()
        width, height = self.width, self.height

        grid.itemAt(height + 1).widget().setParent(None)
        grid.itemAt(height + width - 1).widget().setParent(None)
        grid.itemAt(height).widget().setParent(None)
        for i in reversed(range(height)):
            for j in reversed(range(width)):
                grid.itemAt(i * height + j).widget().setParent(None)


    def move_current_up(self):
        """Moves the player up and draws the new field."""
        self.game.move_current_up()
        self.clear()
        self.draw()
        if self.game.state is State.won:
            self.message(1)
        if self.game.state is State.lost:
            self.message(2)

    def move_current_down(self):
        """Moves the player down, draws the new field and checks for end of level."""
        self.game.move_current_down()
        self.clear()
        self.draw()
        if self.game.x == self.height - 1 and self.game.y == self.width - 1:
            if self.game.player.enough_stars():
                self.switch_levels()
            else:
                self.message(0)
        if self.game.state is State.won:
            self.message(1)
        if self.game.state is State.lost:
            self.message(2)

    def move_current_left(self):
        """Moves the player left and draws the new field."""
        self.game.move_current_left()
        self.clear()
        self.draw()
        if self.game.state is State.won:
            self.message(1)
        if self.game.state is State.lost:
            self.message(2)

    def move_current_right(self):
        """Moves the player right, draws the new field and checks for end of level."""
        self.game.move_current_right()
        self.clear()
        self.draw()
        if self.game.x == self.height - 1 and self.game.y == self.width - 1:
            if self.game.player.enough_stars():
                self.switch_levels()
            else:
                self.message(0)
        if self.game.state is State.won:
            self.message(1)
        if self.game.state is State.lost:
            self.message(2)

    def move_x(self, place, way):
        """Specifies the direction of moving of a X."""
        letter = way[0]
        if letter == 'u':
            self.game.move_x_up(place)
        if letter == 'd':
            self.game.move_x_down(place)
        if letter == 'l':
            self.game.move_x_left(place)
        if letter == 'r':
            self.game.move_x_right(place)
        way += letter
        way.pop(0)

    def keyPressEvent(self, event):
        if self.game.state is State.paused:
            key = event.key()
            if key == Qt.Key_P:
                self.unpause()
            else:
                super(Field, self).keyPressEvent(event)
            return
        if self.game.state is not State.running:
            super(Field, self).keyPressEvent(event)
            return
        key = event.key()
        if key == Qt.Key_Up:
            self.move_current_up()
        elif key == Qt.Key_Down:
            self.move_current_down()
        elif key == Qt.Key_Left:
            self.move_current_left()
        elif key == Qt.Key_Right:
            self.move_current_right()
        elif key == Qt.Key_P:
            self.pause()
        else:
            super(Field, self).keyPressEvent(event)

    def timerEvent(self, event):
        if self.game.state is not State.running:
            super(Field, self).timerEvent(event)
            return
        lev = self.game.level - 1
        if event.timerId() == self.timer.timerId() and self.ways.ways[lev] != []:
            for moving_x in self.ways.ways[lev]:
                self.move_x(moving_x['place'], moving_x['way'])
            self.clear()
            self.draw()
            if self.game.state is State.lost:
                self.message(2)
        else:
            super(Field, self).timerEvent(event)

    def switch_levels(self):
        self.game.new_level()
        self.mat = self.game.field
        self.clear()
        self.draw()

    def pause(self):
        self.game.pause()
        self.clear()
        self.draw()

    def unpause(self):
        self.game.unpause()
        self.clear()
        self.draw()

    def message(self, text_no):
        texts = [
            "You must collect all {} stars to continue!".format(self.game.player.STARS),
            "You win! Congratulations!",
            "Game over! Good luck next time!"]
        msgBox = QMessageBox()
        msgBox.setText(texts[text_no])
        msgBox.exec_()
예제 #48
0
class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.setWindowTitle('Tetris')
        self.setWindowIcon(QtGui.QIcon('Photo/TIcon.jpg'))

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ex = ChangeSize()
        self.ex.SizeSignal.connect(self.updateFrame)

        self.setChildrenFocusPolicy(QtCore.Qt.NoFocus)

        self.timer = QBasicTimer()
        self.curSpeed = 1000
        self.timer.start(self.curSpeed, self)

        self.timerLevel = QBasicTimer()
        self.timerLevel.start(20000, self)

        self.ui.pushButton.clicked.connect(self.updateFrame)

        self.ui.frame.curshape.shape = self.ui.widget.curshape.futureShape
        self.ui.frame.update()

        # Верхняя панель
        settings = QAction(QtGui.QIcon('Photo/Settings.jpg'), 'Size', self)
        settings.setShortcut('Ctrl+S')
        settings.triggered.connect(self.showDialogSize)
        settings.setStatusTip('Change size')
        fileMenu = self.ui.menubar.addMenu('&Settings')
        fileMenu.addAction(settings)

        self.ui.widget.msg2Statusbar[str].connect(
            self.ui.statusbar.showMessage)

        self.loadStyleSheets()

    def loadStyleSheets(self):
        style = "static/style.css"
        with open(style, "r") as f:
            self.setStyleSheet(f.read())

    def showDialogSize(self):
        self.ui.widget.pause = True
        self.ui.widget.msg2Statusbar.emit(' Pause')
        self.stopTime()
        self.ex.show()

    def startTimeAgain(self):
        self.timer.start(self.curSpeed, self)
        self.timerLevel.start(20000, self)

    def stopTime(self):
        self.timer.stop()
        self.timerLevel.stop()

    def updateFrame(self):
        self.stopTime()

        self.curSpeed = 1000
        self.ui.widget.fail = False
        self.ui.widget.pause = False
        self.ui.widget.clearBoard()
        self.ui.widget.newFigure()
        self.ui.widget.update()
        self.ui.frame.curshape.shape = self.ui.widget.curshape.futureShape
        self.ui.frame.update()
        self.ui.widget.count = 0
        self.ui.widget.curLevel = 1

        self.startTimeAgain()

    def keyPressEvent(self, event):
        key = event.key()
        if self.ui.widget.fail or self.ui.widget.pause:
            pass
        if not self.ui.widget.fail and not self.ui.widget.pause:
            if key == QtCore.Qt.Key_Space:
                self.ui.widget.drop()

            if key == QtCore.Qt.Key_Right:
                self.ui.widget.tryMoveX(1)

            if key == QtCore.Qt.Key_Left:
                self.ui.widget.tryMoveX(-1)

            if key == QtCore.Qt.Key_Down:
                self.ui.widget.curshape.coords = self.ui.widget.curshape.rotateShape(
                    1, self.ui.widget.curshape, self.ui.widget.board)
                self.ui.widget.update()
            if key == QtCore.Qt.Key_Up:
                self.ui.widget.curshape.coords = self.ui.widget.curshape.rotateShape(
                    -1, self.ui.widget.curshape, self.ui.widget.board)
                self.ui.widget.update()

        if key == QtCore.Qt.Key_P:
            self.ui.widget.pause = not self.ui.widget.pause
            if self.ui.widget.pause:
                self.stopTime()
                self.ui.widget.msg2Statusbar.emit(' Pause')
            elif not self.ui.widget.fail:
                self.startTimeAgain()

        if key == QtCore.Qt.Key_Escape:
            self.ex.close()
            self.close()

    def timerEvent(self, event):
        if event.timerId() == self.timerLevel.timerId():
            self.curSpeed = self.curSpeed // 1.2
            self.ui.widget.curLevel += 1
            self.startTimeAgain()

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

            if self.ui.widget.fail:
                self.ui.widget.msg2Statusbar.emit('Try Again')
                self.stopTime()
                self.ui.lineEdit.setText('FAIL: All count - ' +
                                         str(self.ui.widget.count))
                self.ui.pushButton.setText('Return?')
            else:
                self.ui.widget.msg2Statusbar.emit('Game Start!')
                self.ui.widget.gravity()
                self.setTextLine()
                self.ui.frame.curshape.shape = self.ui.widget.curshape.futureShape
                self.ui.widget.update()
                self.ui.frame.update()

    def setTextLine(self):
        text = 'Count - '
        text += str(self.ui.widget.count)

        level = 'Level: '
        level += str(self.ui.widget.curLevel)

        self.ui.lineEdit_1.setText(level)
        self.ui.lineEdit.setText(text)
        self.ui.pushButton.setText('GO')

    def setChildrenFocusPolicy(self, policy):
        def recursiveSetChildFocusPolicy(parentQWidget):
            for childQWidget in parentQWidget.findChildren(QWidget):
                childQWidget.setFocusPolicy(policy)
                recursiveSetChildFocusPolicy(childQWidget)

        recursiveSetChildFocusPolicy(self)
예제 #49
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()
예제 #50
0
파일: snake.py 프로젝트: wchpeng/pyqt5_test
class Board(QFrame):

    msg2status_bar = pyqtSignal(str)
    snake_dead_tips = pyqtSignal(str)

    BASE_SPEED = 250
    SPEED = 250
    WIDTH = 20
    HEIGHT = 20
    GAME_OVER_MSG = 'GAME OVER 重新来过?'

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

        self.is_paused = False
        self.game_over = False

        self.timer = QBasicTimer()
        self.snake = SnakeNode()

    def start(self):
        self.timer.start(self.SPEED, self)
        self.paused()

    def timerEvent(self, e):
        if e.timerId() != self.timer.timerId():
            return super(Board, self).timerEvent(e)
        if self.snake.waiting_new_star:
            self.msg2status_bar.emit('score: %d' % len(self.snake.nodes))
            self.snake.waiting_new_star = False
            self.snake.set_new_star()
        self.snake_walk()

    def keyPressEvent(self, event):
        key = event.key()

        if self.is_paused and key != Qt.Key_P:
            return

        if key == Qt.Key_Up:
            self.snake.set_direct_up()
        elif key == Qt.Key_Down:
            self.snake.set_direct_down()
        elif key == Qt.Key_Left:
            self.snake.set_direct_left()
        elif key == Qt.Key_Right:
            self.snake.set_direct_right()
        elif key == Qt.Key_P:
            self.toggle_pause()
        else:
            return super(Board, self).keyPressEvent(event)

    def toggle_pause(self):
        if not self.is_paused:
            self.paused()
        else:
            self.depaused()

    def paused(self):
        self.timer.stop()
        self.msg2status_bar.emit('暂停( p 继续 )')
        self.is_paused = True

    def depaused(self):
        self.timer.start(self.SPEED, self)
        self.msg2status_bar.emit('score: %d' % len(self.snake.nodes))
        self.is_paused = False

    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)
        self.draw_snake(qp)
        self.draw_star(qp)
        qp.end()

    def snake_walk(self):
        # 蛇每次走一步
        if not self.snake.walk():
            self.snake_dead_tips.emit(self.GAME_OVER_MSG)
            self.msg2status_bar.emit('Game Over')
            self.timer.stop()
        self.update()

    def draw_snake(self, qp):
        head_x, head_y = self.snake.nodes[0]
        self.draw_cube(qp, head_x, head_y, SnakeNode.HEADER_COLOR)

        for x, y in self.snake.nodes[1:]:
            self.draw_cube(qp, x, y, SnakeNode.BODY_COLOR)

    def draw_star(self, qp):
        self.draw_cube(qp, self.snake.star_x, self.snake.star_y,
                       SnakeNode.STAR_COLOR)

    def draw_cube(self, qp, x, y, color):
        color = QColor(color)

        width = self.board_cube_width()
        height = self.board_cube_height()
        x *= width
        y *= height

        qp.fillRect(x + 1, y + 1, width - 2, height - 2, color)

        qp.setPen(color.lighter())
        qp.setPen(color.darker())

    def board_cube_width(self):
        return 15
        return self.contentsRect().width() // self.WIDTH

    def board_cube_height(self):
        return 15
        return self.contentsRect().height() // self.HEIGHT
예제 #51
0
class Field(QFrame):
    # объявляем константы поля и скорости
    FieldWidth = 10
    FieldHeight = 22
    Speed = 300

    def __init__(self, parent):
        super().__init__(parent)
        self.initField()
        # используем родительский класс для вывода информации в line edit
        self.parent = parent
        self.pauses_counter = 0

    def initField(self):
        self.timer = QBasicTimer()

        self.is_waiting = False
        self.is_started = False
        self.is_paused = False

        self.current_x = 0
        self.current_y = 0
        self.number_of_removed_lines = 0
        self.field = []

        self.setFocusPolicy(Qt.StrongFocus)
        self.clear_field()

    # возвращает форму фигуры
    def shape_at(self, x, y):
        return self.field[(y * Field.FieldWidth) + x]

    # задает форму фигуры
    def set_shape_at(self, x, y, shape):
        self.field[(y * Field.FieldWidth) + x] = shape

    # возвращает высоту квадрата
    def square_width(self):
        return self.contentsRect().width() // Field.FieldWidth

    # возвращает ширину квадрата
    def square_height(self):
        return self.contentsRect().height() // Field.FieldHeight

    # функции старта и паузы, начинают и останавливают игру соответственно
    def start(self):
        if self.is_paused:
            return

        self.is_started = True
        self.is_waiting = False

        self.number_of_removed_lines = 0

        self.clear_field()
        self.parent.info_line.setText(str(self.number_of_removed_lines))
        self.new_piece()
        self.timer.start(Field.Speed, self)

    def pause(self):
        if not self.is_started:
            return

        self.is_paused = not self.is_paused

        if self.is_paused:
            self.timer.stop()
            self.parent.info_line.setText('Пауза')
            self.pauses_counter += 1

        else:
            self.timer.start(Field.Speed, self)
            self.parent.info_line.setText(str(self.number_of_removed_lines))

        self.update()

    # объявляем правила рисования фигур
    def paintEvent(self, event):
        painter = QPainter(self)
        rect = self.contentsRect()

        # откуда будут появляться
        fieldTop = rect.bottom() - Field.FieldHeight * self.square_height()

        for i in range(Field.FieldHeight):
            for j in range(Field.FieldWidth):
                shape = self.shape_at(j, Field.FieldHeight - i - 1)

                if shape != TetrminoShape.No:
                    self.draw_square(painter,
                        rect.left() + j * self.square_width(),
                        fieldTop + i * self.square_height(), shape)

        if self.piece.shape() != TetrminoShape.No:
            for i in range(4):
                x = self.current_x + self.piece.x(i)
                y = self.current_y - self.piece.y(i)
                self.draw_square(painter, rect.left() + x * self.square_width(),
                    fieldTop + (Field.FieldHeight - y - 1) * self.square_height(),
                    self.piece.shape())

    # привязваем действия к клавишам
    def keyPressEvent(self, event):
        if not self.is_started or self.piece.shape() == TetrminoShape.No:
            super(Field, self).keyPressEvent(event)
            return
        key = event.key()

        # ставит на паузу
        if key == Qt.Key_P:
            self.pause()
            return
        if self.is_paused:
            return

        # двигает фигуру влево
        elif key == Qt.Key_Left:
            self.try_to_move(self.piece, self.current_x - 1, self.current_y)

        # двигает фигуру вправо
        elif key == Qt.Key_Right:
            self.try_to_move(self.piece, self.current_x + 1, self.current_y)

        # вращает фигуру по часовой стрелке
        elif key == Qt.Key_Down:
            self.try_to_move(self.piece.rotate_left(), self.current_x, self.current_y)

        # вращает фигуру против часовой стрелки
        elif key == Qt.Key_Up:
            self.try_to_move(self.piece.rotate_left(), self.current_x, self.current_y)

        # полный спуск вниз
        elif key == Qt.Key_Space:
            self.drop_down()

        # более быстрый спуск вниз
        elif key == Qt.Key_D:
            self.one_line_down()
        else:
            super(Field, self).keyPressEvent(event)

    # создаем таймер чтобы фигура спускалась по шагам
    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            if self.is_waiting:
                self.is_waiting = False
                self.new_piece()
            else:
                self.one_line_down()
        else:
            super(Field, self).timerEvent(event)

    # очищаем поле
    def clear_field(self):
        for i in range(Field.FieldHeight * Field.FieldWidth):
            self.field.append(TetrminoShape.No)

    # быстрый спуск фигуры вниз
    def drop_down(self):
        newY = self.current_y
        while newY > 0:
            if not self.try_to_move(self.piece, self.current_x, newY - 1):
                break
            newY -= 1
        self.piece_dropped()

    # быстрее чем стандартный и контролируемый спуск
    def one_line_down(self):
        if not self.try_to_move(self.piece, self.current_x, self.current_y - 1):
            self.piece_dropped()

    # функция обозначающая что фигура достигла низа для проверки полной строки
    def piece_dropped(self):
        for i in range(4):
            x = self.current_x + self.piece.x(i)
            y = self.current_y - self.piece.y(i)
            self.set_shape_at(x, y, self.piece.shape())
        self.remove_full_lines()
        if not self.is_waiting:
            self.new_piece()

    # удаляет соболненую строку
    def remove_full_lines(self):
        numFullLines = 0
        rowsToRemove = []
        for i in range(Field.FieldHeight):
            n = 0
            for j in range(Field.FieldWidth):
                if not self.shape_at(j, i) == TetrminoShape.No:
                    n = n + 1
            if n == 10:
                rowsToRemove.append(i)
        rowsToRemove.reverse()
        for m in rowsToRemove:
            for k in range(m, Field.FieldHeight):
                for l in range(Field.FieldWidth):
                        self.set_shape_at(l, k, self.shape_at(l, k + 1))
        numFullLines = numFullLines + len(rowsToRemove)
        if numFullLines > 0:
            self.number_of_removed_lines = self.number_of_removed_lines + numFullLines
            self.parent.info_line.setText(str(self.number_of_removed_lines))
            self.is_waiting = True
            self.piece.set_shape(TetrminoShape.No)
            self.update()

    # создает новую фигуру
    def new_piece(self):
        self.piece = Shape()
        self.piece.set_shape_random()
        self.current_x = Field.FieldWidth // 2
        self.current_y = Field.FieldHeight - 1 + self.piece.min_y()
        if not self.try_to_move(self.piece, self.current_x, self.current_y):
            self.piece.set_shape(TetrminoShape.No)
            self.timer.stop()
            self.is_started = False
            self.parent.info_line.setText('Игра окончена')
            self.add_to_data_base()
            self.message()

    # по заверщению игры добавляет статистику в базу данных
    def add_to_data_base(self):
        lines = self.number_of_removed_lines
        pauses = self.pauses_counter
        con = sqlite3.connect("tetris_statistics.db")
        cursor = con.cursor()
        cursor.execute(f"INSERT INTO statistics VALUES ({lines}, {pauses})")
        con.commit()

    # сообщение о проигрыше
    def message(self):
        QMessageBox.about(self, "Игра окончена", "Вы проиграли")

    # сдвиг фигуры в пределах границ поля
    def try_to_move(self, new_piece, newX, newY):
        for i in range(4):
            x = newX + new_piece.x(i)
            y = newY - new_piece.y(i)
            if x < 0 or x >= Field.FieldWidth or y < 0 or y >= Field.FieldHeight:
                return False
            if self.shape_at(x, y) != TetrminoShape.No:
                return False
        self.piece = new_piece
        self.current_x = newX
        self.current_y = newY
        self.update()
        return True

    # рисует единичный квадрат фигуры
    def draw_square(self, painter, x, y, shape):
        colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
                      0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]
        color = QColor(colorTable[shape])
        painter.fillRect(x + 1, y + 1, self.square_width() - 2,
            self.square_height() - 2, color)
        painter.setPen(color.lighter())
        painter.drawLine(x, y + self.square_height() - 1, x, y)
        painter.drawLine(x, y, x + self.square_width() - 1, y)
        painter.setPen(color.darker())
        painter.drawLine(x + 1, y + self.square_height() - 1,
            x + self.square_width() - 1, y + self.square_height() - 1)
        painter.drawLine(x + self.square_width() - 1,
            y + self.square_height() - 1, x + self.square_width() - 1, y + 1)
예제 #52
0
파일: frames.py 프로젝트: slh0302/pyLabel
class Tracker_window(QtWidgets.QMainWindow):
    def __init__(self):
        super(Tracker_window, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.cwd = os.getcwd()
        self.scene = None
        self.printer = None
        self.draw_w = 0
        self.draw_h = 0
        self._func_bind()
        self.cv_cap_loader = None
        self.video_path = ""
        self.save_path = self.cwd
        self.save_name = 'results.txt'
        self.tacker_status = False
        self.cuda_state = torch.cuda.is_available()
        self.tracker_net = init_net(gpus=0,
                                    rel_path=os.path.join(
                                        __prefix_path__, '../checkpoint/'),
                                    cuda_state=self.cuda_state)
        self.total_frames = 0
        self.before_img = None
        self.cur_img = None
        self.cur_frames = 0
        """ reinit status """
        self.skip_frame = 0
        self.before_frame = 0
        self.move_value = 1
        self.reinit_status = False
        """ reinit status """
        self.frameRate = 0
        self.tracker_res = []
        self.thread_status = []
        self.img_scale_ratio = []  # w, h
        self.frame_state = []
        self.stopEvent = threading.Event()
        self.stopEvent.clear()
        self.timer = QBasicTimer()
        self.pause_status = False
        self.timer.start(1000, self)

        # train detector model
        self.train_dialog_ui = Ui_Dialog()
        self.train_dialog = QDialog()
        self.train_dialog_ui.setupUi(self.train_dialog)
        self.model_name = ""
        self.LabelFilePath = "./"
        self.outModelPath = "./"
        self.detect_status = False
        self._func_bind_train_dialog()

    def _func_bind(self):
        self.ui.progressBar.setEnabled(False)
        self.ui.displayLabel.setScaledContents(True)
        # self.ui.plainTextEdit.setEnabled(False)
        self._button_status_change(False)
        self.ui.actionOpen_video.triggered.connect(self.open_event)
        self.ui.actionSave_video.triggered.connect(self.save_event)
        self.ui.actionTrain_Faster_RCNN.triggered.connect(self.showTrainDialog)
        self.ui.redrawPushButton.clicked.connect(self._redraw_button)
        self.ui.startPushButton.clicked.connect(self.start_tracking)
        self.ui.pausPushButton.clicked.connect(self.pause_tracking)
        self.ui.stoPushButton.clicked.connect(self.stop_tracking)
        self.ui.chooseModelButton.clicked.connect(self.open_model_event)
        self.ui.nextPushButton.clicked.connect(self.next_tracking)
        self.ui.prePushButton.clicked.connect(self.prev_tracking)
        self.ui.FramesSpinBox.valueChanged.connect(self.spinValueChange)

    def _func_bind_train_dialog(self):
        self.train_dialog_ui.pushButtonOK.clicked.connect(self.train_ok)
        self.train_dialog_ui.pushButtonCancel.clicked.connect(
            self.train_cancel)
        self.train_dialog_ui.pushButtonLabelPath.clicked.connect(
            self.trainDialog_openLabel)
        self.train_dialog_ui.pushButtonOutModel.clicked.connect(
            self.trainDialog_outputPath)

    def _button_status_change(self, status, need_detect=False):
        self.ui.startPushButton.setEnabled(status)
        self.ui.pausPushButton.setEnabled(status)
        self.ui.redrawPushButton.setEnabled(status)
        self.ui.stoPushButton.setEnabled(status)
        self.ui.prePushButton.setEnabled(status)
        self.ui.nextPushButton.setEnabled(status)
        # self.ui.chooseModelButton.setEnabled(status)
        self.ui.FramesSpinBox.setEnabled(status)
        if not need_detect:
            self.ui.turnDetectorButton.setEnabled(status)

    def _write_logs_to_plain_text(self, text):
        self.ui.textBrowser.append(text)

    def _redraw_button(self):
        self.ui.displayLabel.setdrawDoneStatus(self.cur_img.copy(),
                                               self.img_scale_ratio)
        if self.cur_frames != 0:
            self.reinit_status = True
            self.ui.startPushButton.setText("re-start")
            self.ui.startPushButton.setEnabled(True)

    def _coord_to_text(self, x, y):
        return "X: %d, Y: %d" % (int(x), int(y))

    def _fresh_progresssBar(self):
        if self.total_frames != 0:
            self.ui.progressBar.setValue(
                int(self.cur_frames / self.total_frames * 100))

    def _set_img_ratio(self, img_wh):
        img_w = img_wh[1]
        img_h = img_wh[0]
        self.draw_h = self.ui.displayLabel.size().height()
        self.draw_w = self.ui.displayLabel.size().width()
        self.img_scale_ratio = [
            1.0 * img_w / self.draw_w, 1.0 * img_h / self.draw_h
        ]
        self._write_logs_to_plain_text("Img scale w: %.2f h: %.2f" %
                                       tuple(self.img_scale_ratio))

    def open_event(self):
        fileName_, f_type = QFileDialog.getOpenFileName(
            self, "Open videos", self.cwd,
            'All Files (*);;Mp4 (*.mp4);;Avi (*.avi)')
        if fileName_ == "":
            print("no files")
            return

        if check_filters(fileName_):
            self.video_path = fileName_
            self.init_trackers()
            print(fileName_, f_type)
        else:
            print(fileName_, ' is wrong!')
            return

    def open_model_event(self):
        fileName_, f_type = QFileDialog.getOpenFileName(
            self, "Open models", self.cwd,
            'All Files (*);;pth (*.pth);;Avi (*.model)')
        if fileName_ == "":
            print("no files")
            return

        if os.path.getsize(fileName_) > 100:
            self.model_name = fileName_
            if self.load_model(self.model_name):
                self.ui.turnDetectorButton.setEnabled(True)

            print(fileName_, f_type)
        else:
            print(fileName_, ' is wrong!')
            return

    def load_model(self, filename):
        if os.path.exists(filename):
            # try:
            #     # with open(filename, 'rb') as f:
            #
            # except:

            return True
        else:
            return False

    def save_event(self):
        fileName_, f_type = QFileDialog.getSaveFileName(self,
                                                        "Save videos",
                                                        self.cwd,
                                                        initialFilter='*.txt')
        if fileName_ == "":
            print('use default files')
            out_res_path = os.path.join(self.save_path, self.save_name)
        else:
            self.save_path = os.path.dirname(fileName_)
            self.save_name = os.path.basename(fileName_)
            out_res_path = os.path.join(self.save_path, self.save_name)
            self.LabelFilePath = out_res_path
            print('new path: ', out_res_path)

        if len(self.tracker_res) != 0:
            t1 = threading.Thread(target=save_files,
                                  args=(out_res_path, self.tracker_res))
            t1.start()
        else:
            print(fileName_, ' can\'t save, because the empty res')

        print(fileName_)

    def reinit_tracker(self):
        self.before_img = None
        self.cur_img = None
        self.cur_frames = 0
        self.frameRate = 0
        self.skip_frame = 0
        self.before_frame = 0
        # self.tracker_res = []

    def init_trackers(self):
        if self.total_frames != 0 and self.cv_cap_loader.isOpened():
            self.cv_cap_loader.release()
            self.cur_frames = 0

        if self.cur_frames != 0:
            self.cur_frames = 0

        self.tracker_res = []

        self.cv_cap_loader = cv2.VideoCapture(self.video_path)
        self.total_frames = self.cv_cap_loader.get(7)
        self.frameRate = self.cv_cap_loader.get(cv2.CAP_PROP_FPS)
        if self.cv_cap_loader.isOpened():
            ret, frame = self.cv_cap_loader.read()
            if ret:
                # self.scene.clear()
                self.cur_img = frame.copy()
                height, width, bytesPerComponent = frame.shape
                cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
                bytesPerLine = 3 * width
                QImg = QImage(frame.data, width, height, bytesPerLine,
                              QImage.Format_RGB888)
                pix = QPixmap.fromImage(QImg)
                self.ui.displayLabel.setPixmap(pix)
                self._write_logs_to_plain_text('Read Video done.')
                self.ui.startPushButton.setEnabled(True)
                self.ui.progressBar.setEnabled(True)
                self.ui.redrawPushButton.setEnabled(True)
                self._fresh_progresssBar()
                self._set_img_ratio(frame.shape)
                self.ui.displayLabel.setNewFrames()
                self.ui.displayLabel.setdrawDoneStatus(self.cur_img.copy(),
                                                       self.img_scale_ratio)

    def start_tracking(self):

        if self.stopEvent.is_set():
            self.stopEvent.clear()

        if self.ui.startPushButton.text() != 'Start':
            if self.before_frame != 0:
                self.cur_frames = self.before_frame

            self.tracker_res = self.tracker_res[:self.cur_frames + 1]
            self.ui.progressBar.setValue(
                int(self.cur_frames / self.total_frames * 100))
            if draw_state.draw_done:
                x0, y0, x1, y1 = self.ui.displayLabel.return_x_y()
            else:
                x0, y0, x1, y1 = self.tracker_res[self.cur_frames][1:-1]

            self.tracker_res.pop()
            self._write_logs_to_plain_text("re-start at: " +
                                           self._coord_to_text(x0, y0))
            self._write_logs_to_plain_text("re-start at: " +
                                           self._coord_to_text(x0, y0))
            ori_x, ori_x1 = x0 * self.img_scale_ratio[
                0], x1 * self.img_scale_ratio[0]
            ori_y, ori_y1 = y0 * self.img_scale_ratio[
                1], y1 * self.img_scale_ratio[1]
            frame_bbox = [ori_x, ori_y, ori_x1 - ori_x, ori_y1 - ori_y]
            self.tracker_res.append([self.cur_frames + 1] + frame_bbox + [2.0])
            self.frame_state = init_track(self.tracker_net, self.cur_img,
                                          frame_bbox)
            self.ui.startPushButton.setText("Start")
            self.ui.startPushButton.setEnabled(False)
            self.ui.pausPushButton.click()
        else:
            if draw_state.draw_done:
                self.ui.progressBar.setValue(0)
                x0, y0, x1, y1 = self.ui.displayLabel.return_x_y()
                self._write_logs_to_plain_text(self._coord_to_text(x0, y0))
                self._write_logs_to_plain_text(self._coord_to_text(x1, y1))
                ori_x, ori_x1 = x0 * self.img_scale_ratio[
                    0], x1 * self.img_scale_ratio[0]
                ori_y, ori_y1 = y0 * self.img_scale_ratio[
                    1], y1 * self.img_scale_ratio[1]
                frame_bbox = [ori_x, ori_y, ori_x1 - ori_x, ori_y1 - ori_y]
                self.tracker_res.append([self.cur_frames + 1] + frame_bbox +
                                        [2.0])
                self.frame_state = init_track(self.tracker_net,
                                              self.cur_img,
                                              frame_bbox,
                                              cuda_state=self.cuda_state)
                self.ui.startPushButton.setEnabled(False)
                self.ui.pausPushButton.setEnabled(True)
                self.ui.redrawPushButton.setEnabled(False)
                self.ui.stoPushButton.setEnabled(True)
                th = threading.Thread(target=self.tracking)
                th.start()
            else:
                self._write_logs_to_plain_text("Bbox undone")

    def tracking(self):
        while self.cv_cap_loader.isOpened():
            if True == self.stopEvent.is_set():
                self.stopEvent.clear()
                break
            success, frame = self.cv_cap_loader.read()
            if success:
                self.cur_frames += 1
                self.before_img = self.cur_frames
                self.cur_img = frame.copy()
                self.frame_state = SiamRPN_track(self.frame_state,
                                                 frame,
                                                 cuda_state=self.cuda_state)
                res = cxy_wh_2_rect(self.frame_state['target_pos'],
                                    self.frame_state['target_sz'])
                self.tracker_res.append([self.cur_frames + 1] + list(res) +
                                        [self.frame_state['score']])
                if self.cur_frames % 2 == 0:
                    # TODO: skip frame changes
                    height, width, bytesPerComponent = frame.shape
                    frame = rect_box(frame, res, self.frame_state['score'],
                                     self.cur_frames + 1)
                    cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
                    bytesPerLine = 3 * width
                    QImg = QImage(frame.data, width, height, bytesPerLine,
                                  QImage.Format_RGB888)
                    pix = QPixmap.fromImage(QImg)
                    self.ui.displayLabel.setPixmap(pix)
            else:
                self.cv_cap_loader.release()
                self.ui.stoPushButton.click()
                # self._button_status_change(False)
                break

            if self.stopEvent.is_set() == False:
                time.sleep(0.02)

    def call_backlog(self, msg):
        self.pbar.setValue(int(msg))

    def timerEvent(self, event):
        if self.total_frames != 0:
            self._fresh_progresssBar()
            if not self.cv_cap_loader.isOpened():
                self.cur_frames = 0

    def pause_tracking(self):
        if self.ui.pausPushButton.text() == 'Pause':
            self.stopEvent.set()
            time.sleep(0.5)
            self.pause_status = True
            """ draw res """
            frame = self.cur_img.copy()
            res = self.tracker_res[self.cur_frames]
            height, width, bytesPerComponent = frame.shape
            frame = rect_box(frame, res[1:-1], res[-1], self.cur_frames + 1)
            cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
            bytesPerLine = 3 * width
            QImg = QImage(frame.data, width, height, bytesPerLine,
                          QImage.Format_RGB888)
            pix = QPixmap.fromImage(QImg)
            self.ui.displayLabel.setPixmap(pix)
            """ end draw res """
            self.ui.pausPushButton.setText('Continue')
            self.ui.prePushButton.setEnabled(True)
            self.ui.nextPushButton.setEnabled(True)
            self.ui.FramesSpinBox.setEnabled(True)
            self.ui.redrawPushButton.setEnabled(True)
        else:
            self.pause_status = False
            self.ui.pausPushButton.setText('Pause')
            self.ui.FramesSpinBox.setEnabled(False)
            self.ui.prePushButton.setEnabled(False)
            self.ui.nextPushButton.setEnabled(False)
            self.ui.redrawPushButton.setEnabled(False)
            self.skip_frame = 0
            self.before_frame = 0
            self.cv_cap_loader.set(cv2.CAP_PROP_POS_FRAMES,
                                   self.cur_frames + 1)
            self.stopEvent.clear()
            th = threading.Thread(target=self.tracking)
            th.start()

    def next_tracking(self):
        frame_skip = self.move_value
        if frame_skip <= 0:
            frame_skip = 1

        if self.skip_frame == 0:
            self.skip_frame = self.cur_frames
        else:
            self.skip_frame = self.before_frame

        if self.skip_frame + frame_skip < self.total_frames:
            self.cv_cap_loader.set(cv2.CAP_PROP_POS_FRAMES,
                                   self.skip_frame + frame_skip)
            _, tmp_frame = self.cv_cap_loader.read()
            self.cur_img = tmp_frame.copy()
            res_id = self.skip_frame + frame_skip
            if res_id < self.cur_frames:
                height, width, bytesPerComponent = tmp_frame.shape
                frame = rect_box(tmp_frame, self.tracker_res[res_id][1:-1],
                                 self.tracker_res[res_id][-1], res_id + 1)
                cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
                bytesPerLine = 3 * width
                QImg = QImage(frame.data, width, height, bytesPerLine,
                              QImage.Format_RGB888)
                pix = QPixmap.fromImage(QImg)
                self.ui.displayLabel.setPixmap(pix)
                self.before_frame = self.skip_frame + frame_skip
            else:
                print("undone!")
        else:
            print(" frames can't over the total videos !")

    def prev_tracking(self):
        frame_skip = self.move_value
        if frame_skip <= 0:
            frame_skip = 1

        if self.skip_frame == 0:
            self.skip_frame = self.cur_frames
        else:
            self.skip_frame = self.before_frame

        if self.skip_frame - frame_skip >= 0:
            self.cv_cap_loader.set(cv2.CAP_PROP_POS_FRAMES,
                                   self.skip_frame - frame_skip)
            _, tmp_frame = self.cv_cap_loader.read()
            self.cur_img = tmp_frame.copy()
            res_id = self.skip_frame - frame_skip
            if res_id >= 0:
                height, width, bytesPerComponent = tmp_frame.shape
                frame = rect_box(tmp_frame, self.tracker_res[res_id][1:-1],
                                 self.tracker_res[res_id][-1], res_id + 1)
                cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
                bytesPerLine = 3 * width
                QImg = QImage(frame.data, width, height, bytesPerLine,
                              QImage.Format_RGB888)
                pix = QPixmap.fromImage(QImg)
                self.ui.displayLabel.setPixmap(pix)
                self.before_frame = self.skip_frame - frame_skip
        else:
            print(" frames can't less the zero !")

    def spinValueChange(self):
        self.move_value = self.ui.FramesSpinBox.value()

    def stop_tracking(self):
        if self.ui.pausPushButton.text() == 'Continue':
            self.ui.pausPushButton.setText('Pause')

        if self.cv_cap_loader.isOpened():
            self.stopEvent.set()
            self.reinit_tracker()
            self.cv_cap_loader.release()
        else:
            self.reinit_tracker()
            self._write_logs_to_plain_text("Done all videos !!")
        self._button_status_change(False, need_detect=self.detect_status)

    """ train dialog"""

    def showTrainDialog(self):
        self.train_dialog.setWindowModality(Qt.ApplicationModal)
        self.train_dialog_ui.lineEditLabelPath.setText(self.LabelFilePath)
        self.train_dialog.exec_()

    def trainDialog_openLabel(self):
        fileName_, f_type = QFileDialog.getOpenFileName(
            self, "Open Labels", self.cwd, 'All Files (*);;TXT (*.txt)')
        if fileName_ == "":
            print("no files")
            return

        if ".txt" in fileName_:
            self.LabelFilePath = fileName_
            # self.init_trackers()
            print(fileName_, f_type)
        else:
            print(fileName_, ' is wrong!')
            return

    def trainDialog_outputPath(self):
        fileName_, f_type = QFileDialog.getOpenFileName(
            self, "Out Model", self.cwd, 'All Files (*);;PTH (*.pth)')
        if fileName_ == "":
            print("no files")
            return

        if ".txt" in fileName_:
            self.outModelPath = fileName_
            # self.init_trackers()
            print(fileName_, f_type)
        else:
            print(fileName_, ' is wrong!')
            return

    def train_ok(self):
        self.train_dialog.close()

    def train_cancel(self):
        self.train_dialog.close()
class Board(QWidget):
    TileCount = int(FIELD_SIZE / TILE_SIZE)
    RefreshSpeed = 33

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

        self.obstacleArray = Utils.create_example_array(Board.TileCount)

        # Create an additional obstacle list from array
        # storing the position values of every obstacle.
        # Since we don't change the obstacleArray,
        # this call is only needed once.
        self.obstacle_list = Utils.generate_obstacle_list(
            self.obstacleArray, Board.TileCount)

        self.timer = QBasicTimer()

        # TODO watch out that it doesn't get too big
        self.time_stamp = -1

        # A list of DataRobots
        self.robots = []

        self.bullets = set()

        self.collision_scenarios = dict()

        self.key_states = dict()
        self.stateless_keys = dict()

        self.create_scenario()

        self.initiate_key_listening()

        for robot in self.robots:
            robot.start()

        self.timer.start(Board.RefreshSpeed, self)

    def create_scenario(self):
        """Here, you can implement the scenario on the board.
        """

        # First add the robots.
        pos1 = (500, 750, 75, 0, 0)
        mv1 = RunMovement()
        robo1 = self.construct_robot(TILE_SIZE * 4,
                                     mv1,
                                     20,
                                     10,
                                     pos1,
                                     max_life=5)
        robo1.set_alert_flag()
        self.deploy_robot(robo1)

        pos2 = (45, 845, 0, 0, 0)
        mv2 = ChaseMovementGun(0)
        gun = RoboGun()
        RoboGun.trigun_decorator(gun)
        robo2 = self.construct_robot(TILE_SIZE * 3,
                                     mv2,
                                     12,
                                     10,
                                     pos2,
                                     gun=gun,
                                     max_life=1)
        robo2.setup_player_control(
            control_scheme=ControlScheme.player_two_scheme)
        # robo2.set_alert_flag()
        self.deploy_robot(robo2)

        pos3 = (965, 35, 240, 0, 0)
        mv3 = PermanentGunMovement()
        robo3 = self.construct_robot(TILE_SIZE * 2.5,
                                     mv3,
                                     5,
                                     15,
                                     pos3,
                                     v_max=12,
                                     v_alpha_max=30)
        robo3.set_alert_flag()
        pc = PlayerControl(robo3,
                           ControlScheme.default_scheme,
                           invasive_controls=True,
                           alpha_accel_amt=10)
        robo3.setup_player_control(pc)
        self.deploy_robot(robo3)

        pos4 = (300, 650, 70, 0, 0)
        mv4 = ChaseAvoidMovementGun(0)
        gun4 = RoboGun(bullet_speed=30)
        robo4 = self.construct_robot(TILE_SIZE * 2,
                                     mv4,
                                     15,
                                     15,
                                     pos4,
                                     gun=gun4)
        # robo4.set_alert_flag()
        self.deploy_robot(robo4)

        # Then add scenario recipes.
        # self.create_catch_recipe(0, [3, 1, 2])

    def deploy_robot(self, data_robot):
        self.robots.append(data_robot)

    # TODO we might improve that function
    def initiate_key_listening(self):
        self.setFocusPolicy(Qt.StrongFocus)
        collected_keys_states = dict()
        collected_keys_stateless = dict()
        for robot in self.robots:
            if robot.player_control:
                robot_keys = robot.player_control.control_scheme
                for key, value in robot_keys.items():
                    # TODO distinguish stateless keys from keys with state
                    if not value == ControlScheme.AUTOPILOT_STRING:
                        if key in collected_keys_states:
                            collected_keys_states[key].append(robot)
                        else:
                            collected_keys_states[key] = [robot]
                    else:
                        if key in collected_keys_stateless:
                            collected_keys_stateless[key].append(robot)
                        else:
                            collected_keys_stateless[key] = [robot]

        for key, value in collected_keys_states.items():
            self.key_states[key] = dict(is_pressed=False,
                                        was_pressed=False,
                                        targets=tuple(value))

        for key, value in collected_keys_stateless.items():
            self.stateless_keys[key] = tuple(value)

    def construct_robot(self,
                        radius,
                        movement_funct,
                        a_max,
                        a_alpha_max,
                        position,
                        fov_angle=90,
                        v_max=50,
                        v_alpha_max=90,
                        max_life=3,
                        respawn_timer=3,
                        gun=None):
        """
        Create a new robot with given parameters.
        You can add it to the board using deploy_robot().
        """

        # Create robot body with its set parameters.
        base_robot = BaseRobot(radius,
                               a_max,
                               a_alpha_max,
                               fov_angle=fov_angle,
                               v_max=v_max,
                               v_alpha_max=v_alpha_max,
                               max_life=max_life,
                               respawn_timer=respawn_timer)

        # Create autonomous robot unit.
        thread_robot = ThreadRobot(base_robot, movement_funct)

        # Create data representation to be added to tracking of the server.
        data_robot = DataRobot(base_robot, thread_robot)
        # set up communication with thread robot about gun data
        data_robot.setup_gun(gun)
        # a position consists of (x, y, alpha, v, v_alpha) values
        data_robot.place_robot(*position)

        return data_robot

    # ==================================
    # Painter Area
    # ==================================
    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)
        self.drawBoard(qp)
        self.drawObstacles(qp)
        for robot in self.robots:
            self.drawRobot(qp, robot)
        self.drawBullets(qp)
        qp.end()

    def drawBoard(self, qp):
        texture = QPixmap("textures/board.png")
        qp.save()
        source = QRectF(0, 0, 1125, 1125)
        target = QRectF(0, 0, 1000, 1000)
        qp.setOpacity(1)
        qp.drawPixmap(target, texture, source)
        qp.restore()

    def drawObstacles(self, qp):

        for xpos in range(Board.TileCount):
            for ypos in range(Board.TileCount):

                tileVal = self.obstacleArray[xpos][ypos]

                if tileVal == Hazard.Wall:
                    texture = QPixmap("textures/wall.png")
                    qp.save()
                    source = QRectF(0, 0, 10, 10)
                    target = QRectF(xpos * TILE_SIZE, ypos * TILE_SIZE,
                                    TILE_SIZE, TILE_SIZE)
                    qp.drawPixmap(target, texture, source)
                    qp.restore()

                elif tileVal == Hazard.Border:
                    texture = QPixmap("textures/border.png")
                    qp.save()
                    source = QRectF(0, 0, 10, 10)
                    target = QRectF(xpos * TILE_SIZE, ypos * TILE_SIZE,
                                    TILE_SIZE, TILE_SIZE)
                    qp.drawPixmap(target, texture, source)
                    qp.restore()

                elif tileVal == Hazard.Hole:
                    texture = QPixmap("textures/hole.png")
                    qp.save()
                    source = QRectF(0, 0, 10, 10)
                    target = QRectF(xpos * TILE_SIZE, ypos * TILE_SIZE,
                                    TILE_SIZE, TILE_SIZE)
                    qp.drawPixmap(target, texture, source)
                    qp.restore()

    def drawRobot(self, qp, robot):
        texture = QPixmap("textures/robot.png")
        overlay = QRectF(robot.x - robot.radius, robot.y - robot.radius,
                         2 * robot.radius, 2 * robot.radius)
        qp.save()

        if robot.life / robot.max_life == 0:
            life_frac = 0.01
        elif robot.life / robot.max_life >= 0:
            life_frac = robot.life / robot.max_life
        # setting opacity
        robot_op = 1
        overlay_op = 1
        if robot.dead or robot.immune:
            robot_op = 0.7
            overlay_op = 1

        # painting overlay:
        # setting the color to represent health
        if robot.immune:
            R = 0
            G = 0
            B = 255
            A = 100
        elif not robot.dead:
            R = 255 * (1 - life_frac)
            G = 255 * life_frac
            B = 0
            A = 255
        elif robot.dead:
            R = 10
            G = 10
            B = 10
            A = 255
        qp.setBrush(QColor(R, G, B, A))
        # drawing overlay
        qp.setOpacity(overlay_op)
        qp.drawEllipse(overlay)

        # painting robot:
        # mapping the texture to the robot
        qp.translate(robot.x, robot.y)
        qp.rotate(robot.alpha)
        source = QRectF(0, 0, 567, 566)
        target = QRectF(-robot.radius, -robot.radius, 2 * robot.radius,
                        2 * robot.radius)
        # drawing the robot
        qp.setOpacity(robot_op)
        qp.drawPixmap(target, texture, source)

        qp.restore()

    def drawBullets(self, qp):
        texture = QPixmap("textures/bullet.png")
        for bullet in self.bullets:
            bullet_radius = 10
            qp.save()
            qp.translate(bullet.position[0], bullet.position[1])
            source = QRectF(0, 0, 715, 715)
            target = QRectF(-bullet_radius, -bullet_radius, 2 * bullet_radius,
                            2 * bullet_radius)
            qp.drawPixmap(target, texture, source)
            qp.restore()

    # ==================================
    # Scenario Area
    # ==================================

    def create_catch_recipe(self, fugitive, hunters):
        """Adds a new concrete scenario recipe.
        If fugitive is caught, teleport catcher away.
        """

        # TODO make abstract with external callee

        def callee(hunter, board):
            fugitive_bot = board.robots[fugitive]
            fugitive_pos = (fugitive_bot.x, fugitive_bot.y)
            hunter_bot = board.robots[hunter]
            Board.teleport_furthest_corner(fugitive_pos, hunter_bot)

        for h in hunters:
            f = partial(callee, h)
            self.collision_scenarios[(fugitive, h)] = f
            # self.collision_scenarios[(h, fugitive)] = f

    def perform_collision_scenario(self, col_tuple):
        """Collision scenario handler.
        Looks if a collision scenario occured and performs the actions needed.
        """
        if col_tuple in self.collision_scenarios:
            self.collision_scenarios[col_tuple](self)

    # ==================================
    # Vision Area
    # ==================================

    def calculate_vision_board(self, robot):
        """Calculate a list of all obejcts seen by a robot.
        The objects are reduced to their center points for this calculation.
        Returns a list of tuple values for obejcts seen:
        (index in obstacle_Array, obstacle type, distance from robot's center)
        """

        # get the objects representative points
        points = self.obstacle_list * 10 + 5
        point = (robot.x, robot.y)

        # use calculate_angles for the maths
        diffs, dists = Utils.calculate_angles(points, point, robot.alpha,
                                              robot.fov_angle)

        out = []
        for obst, dif, dist in zip(self.obstacle_list, diffs, dists):
            # if angle difference is greater zero, the obejct will not be seen
            if dif <= 0:
                x, y = obst
                data = (obst, self.obstacleArray[x][y], dist)
                out.append(data)

        # out = [[0] * 100 for row in range(100)]
        # for pair in zip(self.obstacle_list, diffs):
        #     if pair[1] <= 0:
        #         x, y = pair[0]
        #         out[x][y] = self.obstacleArray[x][y]

        return out

    def calculate_vision_robots(self, robot):
        """Calculate a list of robots seen by a robot.
        A robot (a) can be seen by robot (x) if:
        - (a) touches (x)
        - (a)s center is in the direct FoV-angle of (x)
        - a point of (a)s radius is in the direct FoV-angle of (x)

        For the last criteria, we check, if (a) intersects one of the rays,
        marking the outline of the FoV.

        Returns an array with entries for each robot:
        The array index equals the robot's position in the server's array.
        Array entries:
        False, if the robot can not be seen.
        A tuple, if the robot is seen:
        (position, distance between the robot's centers)
        """
        point = (robot.x, robot.y)

        # no robot is seen per default.
        result = [False] * len(self.robots)
        point_list = []

        # robots in this list must undergo the angle-check
        # since they don't overlap.
        # this also stops invalid point values
        # from being inserted in calculate_angle.
        calc_list = []
        calc_indices = []

        # distance-check
        for index, rb in enumerate(self.robots):
            # for each robot, get its distance to (x) and calculate,
            # wheather they overlap.
            pos = (rb.x, rb.y)
            check, d = Utils.overlap_check(pos, point, rb.radius, robot.radius)
            # create a list of position and distance for EVERY robot.
            point_list.append((pos, d))

            # the actual overlap-check:
            if check:
                result[index] = (pos, d)
            # add more cases, if you want to propagate the angles as well
            else:
                calc_list.append(pos)
                calc_indices.append(index)

        # angle-check
        angles = []
        if calc_list:
            angles, _ = Utils.calculate_angles(calc_list, point, robot.alpha,
                                               robot.fov_angle)

        for index, dif in zip(calc_indices, angles):
            # if the difference value is positive, the center is not seen.
            if dif <= 0:
                result[index] = point_list[index]

        # ray-check
        # calculate the two border rays of the fov
        ray1 = Utils.vector_from_angle(robot.alpha - robot.fov_angle / 2)
        ray2 = Utils.vector_from_angle(robot.alpha + robot.fov_angle / 2)

        for index, val in enumerate(result):
            # only check robots that are not already seen
            if not val:
                rb = self.robots[index]
                circle = (rb.x, rb.y, rb.radius)
                # again, python helps us out!
                if (Utils.ray_check(point, ray1, circle)
                        or Utils.ray_check(point, ray2, circle)):
                    result[index] = point_list[index]

        # now the list is complete
        return result

    # ==================================
    # Collision Area
    # ==================================

    def calculate_robot(self, poll, robot):
        """Uses current position data of robot robot and acceleration values
        polled from the robot to calculate new position values.
        """

        # unpack robot output
        a, a_alpha = poll

        # checks if acceleration is valid
        a = Utils.limit(a, -robot.a_max, robot.a_max)

        # checks if angle acceleration is valid
        a_alpha = Utils.limit(a_alpha, -robot.a_alpha_max, robot.a_alpha_max)

        # calculates velocities
        new_v = Utils.limit(robot.v + a, -1 * robot.v_max, robot.v_max)
        new_v_alpha = Utils.limit(robot.v_alpha + a_alpha,
                                  -1 * robot.v_alpha_max, robot.v_alpha_max)

        # calculates the new position - factors in collisions
        new_position_col = self.col_robots_walls(robot, new_v, new_v_alpha)

        # re-place the robot on the board
        Board.place_robot(robot, *new_position_col)
        # sends tuple to be used as "sensor_data"
        return new_position_col

    def calculate_position(self, robot, new_v, new_v_alpha):
        # calculates alpha
        new_alpha = robot.alpha + new_v_alpha
        # TODO confirm no bugs
        new_alpha = new_alpha % 360
        radian = ((new_alpha - 90) / 180 * math.pi)

        # calculates x coordinate, only allows values inside walls
        new_x = Utils.limit(robot.x + new_v * math.cos(radian), 0, FIELD_SIZE)

        # calculates y coordinate, only allows values inside walls
        new_y = Utils.limit(robot.y + new_v * math.sin(radian), 0, FIELD_SIZE)
        new_position = (new_x, new_y, new_alpha, new_v, new_v_alpha)
        return new_position

    def col_robots_walls(self, robot, new_v, new_v_alpha):
        """Task 2: Here the collision with obstacles is calculated."""

        # calculates the new position without factoring in any collisions
        position_no_col = self.calculate_position(robot, new_v, new_v_alpha)
        current_testing_pos = position_no_col

        # loop until the current position doesn't produce any collision
        collided = False

        # calculate the boundaries of the area where tiles will be tested
        robot_reach = robot.radius + abs(new_v)
        leftmost_tile = Utils.limit(int((robot.x - robot_reach) / TILE_SIZE),
                                    0, Board.TileCount)
        rightmost_tile = Utils.limit(
            int((robot.x + robot_reach) / TILE_SIZE) + 1, 0, Board.TileCount)
        upmost_tile = Utils.limit(int((robot.y - robot_reach) / TILE_SIZE), 0,
                                  Board.TileCount)
        downmost_tile = Utils.limit(
            int((robot.y + robot_reach) / TILE_SIZE) + 1, 0, Board.TileCount)

        while True:
            max_sub = 0

            # tests all 100x100 tiles in the array for collision
            for tile_x in range(leftmost_tile, rightmost_tile):
                for tile_y in range(upmost_tile, downmost_tile):
                    tile_type = self.obstacleArray[tile_x][tile_y]
                    if tile_type:
                        # takes the position where it doesn't collide
                        # and the amount it backtracked
                        sub, current_pos_col = self.col_robots_walls_helper(
                            current_testing_pos, robot, tile_x, tile_y)

                        # saves position with the most backtracking
                        if abs(sub) > abs(max_sub):
                            max_sub = sub
                            final_pos_col = current_pos_col
                            final_tile_type = tile_type

            # if this iteration (one position) produced any collisions
            # the final position gets tested again
            if max_sub:
                current_testing_pos = final_pos_col
                # test if this adjusted position needs more adjusting
                collided = True
            else:
                break

        # if there was na collision at all, the original position is returned
        if not collided:
            final_pos_col = position_no_col

        elif final_tile_type == 3:
            # TODO: change behavior for hitting a hole here
            robot.deal_damage()

        return final_pos_col

    def col_robots_walls_helper(self, new_position, robot, tile_x, tile_y):
        max_v = new_position[3]
        # checks if the robot collides with a specific tile

        # calc the coordinates of the given tile
        tile_origin = QPoint(tile_x * TILE_SIZE, tile_y * TILE_SIZE)

        # loop terminates when there is no collision
        sub_from_v = 0
        while True:
            # recalculate the position with the adjusted v
            new_position_col = self.calculate_position(robot,
                                                       max_v - sub_from_v,
                                                       new_position[4])
            robot_center = QPoint(new_position_col[0], new_position_col[1])

            colliding = Utils.check_collision_circle_rect(
                robot_center, robot.radius, tile_origin, TILE_SIZE, TILE_SIZE)
            if abs(sub_from_v) <= abs(max_v) and colliding:
                if max_v > 0:
                    sub_from_v += 1
                else:
                    sub_from_v -= 1
            else:
                break

        # return the amount of backtracking (0 if no collision)
        # and the closest position that is collision free
        return sub_from_v, new_position_col

    # TODO we might improve that function
    def check_collision_robots(self):
        s = len(self.robots)
        for i in range(s):
            for j in range(s):
                if not i == j:
                    bot1 = self.robots[i]
                    bot2 = self.robots[j]
                    c1 = (bot1.x, bot1.y)
                    r1 = bot1.radius
                    c2 = (bot2.x, bot2.y)
                    r2 = bot2.radius
                    check, _ = Utils.overlap_check(c1, c2, r1, r2)
                    if check:
                        self.perform_collision_scenario((i, j))

    # ==================================
    # Gun/Bullet Area
    # ==================================

    def calculate_shoot_action(self):
        for robot in self.robots:
            maybe_bullet = robot.perform_shoot_action()
            if maybe_bullet:
                self.bullets.add(maybe_bullet)

    def calculate_bullets(self):
        """
        Here, the bullet movement happens.
        Check for collision with walls and despawn the bullet.
        Check for collision with robots and kill the robot (despawn the bullet)
        """

        for bullet in self.bullets.copy():
            # move
            initial_position = bullet.position
            for test_speed in range(int(bullet.speed)):

                direction_vec = Utils.vector_from_angle(bullet.direction)
                movement_vec = direction_vec * test_speed
                new_position = initial_position + movement_vec
                bullet.position = new_position

                # perform collision with walls and robots
                if (self.col_bullet_walls(bullet)
                        or self.col_robots_bullets(bullet)):
                    break

        # respawn the robots
        # for robot in self.robots:
        #     if robot.dead:
        #         pos = (robot.x, robot.y)
        #         Board.teleport_furthest_corner(pos, robot)
        #         robot.dead = False

    def col_robots_bullets(self, bullet):
        for robot in self.robots:
            robot_center = (robot.x, robot.y)
            distance = Utils.distance(robot_center, bullet.position)
            if distance <= robot.radius:
                robot.deal_damage()
                # robot.dead = True
                self.bullets.remove(bullet)
                return True
        return False

    def col_bullet_walls(self, bullet):
        position = bullet.position

        tile_x = int(position[0] / TILE_SIZE)
        tile_x = Utils.limit(tile_x, 0, Board.TileCount - 1)

        tile_y = int(position[1] / TILE_SIZE)
        tile_y = Utils.limit(tile_y, 0, Board.TileCount - 1)

        if self.obstacleArray[tile_x][tile_y] != 0:
            self.bullets.remove(bullet)
            return True

        return False

    # ==================================
    # Key input Area
    # ==================================

    def keyPressEvent(self, event):
        key = event.key()

        # handle stateless keys
        if key in self.stateless_keys:
            for robot in self.stateless_keys[key]:
                robot.enter_key_action(key)

        # set state variables for keys with state
        if key in self.key_states:
            key_dict = self.key_states[key]
            key_dict['is_pressed'] = True
            key_dict['was_pressed'] = True

    def keyReleaseEvent(self, event):
        key = event.key()

        # set state variables for keys with state
        if key in self.key_states:
            key_dict = self.key_states[key]
            key_dict['is_pressed'] = False

    def handle_keys_with_state(self):
        for key, value in self.key_states.items():
            # state is acitve
            if value['is_pressed'] or value['was_pressed']:
                # TODO maybe only call when needed
                value['was_pressed'] = False
                for robot in value['targets']:
                    robot.enter_key_action(key, state=True)
            # state is inactive
            else:
                for robot in value['targets']:
                    robot.enter_key_action(key, state=False)

        # perform actions for entwined keys
        for robot in self.robots:
            robot.finish_key_actions()

    # ==================================
    # Main Loop
    # ==================================

    def timerEvent(self, event):
        """The game's main loop.
        Called every tick by active timer attribute of the board.
        """
        # TODO use delta-time to interpolate visuals

        self.time_stamp += 1

        self.handle_keys_with_state()

        self.calculate_shoot_action()

        self.calculate_bullets()

        for robot in self.robots:
            poll = robot.poll_action_data()
            self.calculate_robot(poll, robot)
            # if collision:
            #     m = self.create_bonk_message(collision)
            #     robot.send_sensor_data(m)

        if self.time_stamp % 10 == 0:
            m = self.create_alert_message()
            for robot in self.robots:
                if robot.alert_flag:
                    robot.send_sensor_data(m)

        # TODO we might improve that function
        self.check_collision_robots()

        for robot in self.robots:
            v = self.create_vision_message(robot)
            robot.send_sensor_data(v)
            m = self.create_position_message(robot)
            robot.send_sensor_data(m)

        # update visuals
        self.update()

    # ==================================
    # Message Area
    # ==================================

    def create_alert_message(self):
        data = []

        for robot in self.robots:
            data.append((robot.x, robot.y))

        return SensorData(SensorData.ALERT_STRING, data, self.time_stamp)

    # TODO this is just a frame implementation.
    def create_bonk_message(self, collision):
        print('B O N K')

        data = None
        return SensorData(SensorData.BONK_STRING, data, self.time_stamp)

    def create_position_message(self, robot):

        data = (robot.x, robot.y, robot.alpha, robot.v, robot.v_alpha)
        return SensorData(SensorData.POSITION_STRING, data, self.time_stamp)

    def create_vision_message(self, robot):
        "New message type for FoV-data of a robot."

        # list of wall object tuples:
        # ((xpos, ypos), type, distance)
        board_data = self.calculate_vision_board(robot)

        # list of robot object tuples:
        # ((xpos, ypos), distance)
        robot_data = self.calculate_vision_robots(robot)

        data = (board_data, robot_data)
        return SensorData(SensorData.VISION_STRING, data, self.time_stamp)

    # ==================================
    # Static positioning methods
    # ==================================

    @staticmethod
    def place_robot(robot, x, y, alpha, v, v_alpha):
        """Re-places a robot with given position values.
        No sensor data sent.
        """
        robot.x = x
        robot.y = y
        robot.alpha = alpha
        robot.v = v
        robot.v_alpha = v_alpha

    @staticmethod
    def teleport_furthest_corner(point, robot):
        """Teleports the robot to a position in the corner
        with the largest distance from point.
        """

        lower_limit = TILE_SIZE + robot.radius + 1
        upper_limit = FIELD_SIZE - TILE_SIZE - robot.radius - 2

        top_left_corner = (lower_limit, lower_limit, 135, 0, 0)
        bot_left_corner = (lower_limit, upper_limit, 45, 0, 0)
        top_right_corner = (upper_limit, lower_limit, 225, 0, 0)
        bot_right_corner = (upper_limit, upper_limit, 315, 0, 0)

        if point[0] > (FIELD_SIZE / 2):
            if point[1] > (FIELD_SIZE / 2):
                position = top_left_corner
            else:
                position = bot_left_corner
        else:
            if point[1] > (FIELD_SIZE / 2):
                position = top_right_corner
            else:
                position = bot_right_corner

        robot.place_robot(*position)
예제 #54
0
class Board(QFrame):
    def __init__(self,parent):
        super().__init__(parent)
        self.dims = parent.dims
        self.parent = parent
        self.initBoard()
        pass

    def initBoard(self):
        if len(sys.argv)>1:
            self.data_size = tuple(map(int,sys.argv[1:])) # For testing
        else:
            self.data_size = (4,4) # Size of the board in tiles, x,y
        self.tile_size = (90,90) # size of each tiles in px, x,y
        self.top_border = (30,30) # The distance from the top left between the border and the first tile
        self.tile_gap = 10 # Pixels between each tiles
        self.data = Tw_internal(*self.data_size) # Keeps track of the values of the tiles and performs all the game logic
        self.timer = QBasicTimer()
        self.setFocusPolicy(Qt.StrongFocus)
        self.start()

        colorCodes = "#fffaea #fcf1cf #ffeeba #ffe9a8 #ffe393 #ffde82 #ff8282 #ff6666 #ff4747 #ff2d2d #ff1414 #ff0000".split(" ")
        self.tile_colours = [QColor(x) for x in colorCodes]
        self.colors = {
            "black":    QColor("#000000"),
            "grey":     QColor(0xa6, 0xae, 0xbc)
        }

        reset_icon = QIcon("./resources/restart.png")
        reset_button = QPushButton(reset_icon, "", self)
        reset_button.clicked.connect(self.restart_button_press)
        reset_button.move(500,50)

        undo_icon = QIcon("./resources/undo.png")
        undo_button = QPushButton(undo_icon,"",self)
        undo_button.clicked.connect(self.undo)
        undo_button.move(500,100)

    def start(self):
        self.timer.start(17,self)

    def timerEvent(self,e):
        if e.timerId() == self.timer.timerId():
            self.update()
    
    def undo(self):
        if self.data.undoable:
            self.data.tiles = self.data.prev
            self.data.undoable = False
            self.data.next()

    def restart(self):
        self.timer.stop()
        self.initBoard()

    def restart_button_press(self):
        reply = QMessageBox.question(self, "Restart?", "Are you sure you want to restart the game?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            self.restart()


    def paintEvent(self,e):
        qp = QPainter(self)
        for y,j in enumerate(self.data.tiles):
            for x,i in enumerate(j):
                x2 = x*(self.tile_size[0] + self.tile_gap) + self.top_border[0]
                y2 = y*(self.tile_size[0] + self.tile_gap) + self.top_border[1]
                if i!=0:
                    index = int(math.log2(i))
                else: index = 0
                try:
                    qp.setBrush(self.tile_colours[index])
                except IndexError:
                    qp.setBrush(self.colors["black"])
                qp.setPen(self.colors["black"])
                qp.drawRect(x2, y2, self.tile_size[0], self.tile_size[1])
                if i!=0:
                    qp.setFont(QFont("Decorative", self.calc_fontsize(i)))
                    qp.setPen(self.colors["grey"])
                    qp.drawText(x2, y2, self.tile_size[0], self.tile_size[1], Qt.AlignCenter, str(i))

    def calc_fontsize(self, v):
        if v<100: return 50
        l = len(str(v))
        a = 50-(5*l)
        if a<=5: return 5
        return a
        
    def keyPressEvent(self,e):
        turn_successful = False
        full = False
        key = e.key()
        if key == Qt.Key_Right:
            turn_successful = self.data.collapse("right")
        if key == Qt.Key_Left:
            turn_successful = self.data.collapse("left")
        if key == Qt.Key_Up:
            turn_successful = self.data.collapse("up")
        if key == Qt.Key_Down:
            turn_successful = self.data.collapse("down")
        
        if turn_successful:
            self.next_turn()

        if self.data.full():
            self.boardFull()

    def boardFull(self):
        self.timer.stop()
        reply = QMessageBox.question(self, "Game Over", "Board is full!. Would you like to play again?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.restart()
        else:
            self.parent.close()

    def closeEvent(self, e):
        e.accept()


    def next_turn(self):
        self.data.next()
예제 #55
0
파일: tetrix.py 프로젝트: Axel-Erfurt/pyqt5
class TetrixBoard(QFrame):
    BoardWidth = 10
    BoardHeight = 22

    scoreChanged = pyqtSignal(int)

    levelChanged = pyqtSignal(int)

    linesRemovedChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        super(TetrixBoard, self).__init__(parent)

        self.timer = QBasicTimer()
        self.nextPieceLabel = None
        self.isWaitingAfterLine = False
        self.curPiece = TetrixPiece()
        self.nextPiece = TetrixPiece()
        self.curX = 0
        self.curY = 0
        self.numLinesRemoved = 0
        self.numPiecesDropped = 0
        self.score = 0
        self.level = 0
        self.board = None

        self.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.setFocusPolicy(Qt.StrongFocus)
        self.isStarted = False
        self.isPaused = False
        self.clearBoard()

        self.nextPiece.setRandomShape()

    def shapeAt(self, x, y):
        return self.board[(y * TetrixBoard.BoardWidth) + x]

    def setShapeAt(self, x, y, shape):
        self.board[(y * TetrixBoard.BoardWidth) + x] = shape   

    def timeoutTime(self):
        return 1000 / (1 + self.level)

    def squareWidth(self):
        return self.contentsRect().width() / TetrixBoard.BoardWidth

    def squareHeight(self):
        return self.contentsRect().height() / TetrixBoard.BoardHeight

    def setNextPieceLabel(self, label):
        self.nextPieceLabel = label

    def sizeHint(self):
        return QSize(TetrixBoard.BoardWidth * 15 + self.frameWidth() * 2,
                TetrixBoard.BoardHeight * 15 + self.frameWidth() * 2)

    def minimumSizeHint(self):
        return QSize(TetrixBoard.BoardWidth * 5 + self.frameWidth() * 2,
                TetrixBoard.BoardHeight * 5 + self.frameWidth() * 2)

    def start(self):
        if self.isPaused:
            return

        self.isStarted = True
        self.isWaitingAfterLine = False
        self.numLinesRemoved = 0
        self.numPiecesDropped = 0
        self.score = 0
        self.level = 1
        self.clearBoard()

        self.linesRemovedChanged.emit(self.numLinesRemoved)
        self.scoreChanged.emit(self.score)
        self.levelChanged.emit(self.level)

        self.newPiece()
        self.timer.start(self.timeoutTime(), self)

    def pause(self):
        if not self.isStarted:
            return

        self.isPaused = not self.isPaused
        if self.isPaused:
            self.timer.stop()
        else:
            self.timer.start(self.timeoutTime(), self)

        self.update()

    def paintEvent(self, event):
        super(TetrixBoard, self).paintEvent(event)

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

        if self.isPaused:
            painter.drawText(rect, Qt.AlignCenter, "Pause")
            return

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

        for i in range(TetrixBoard.BoardHeight):
            for j in range(TetrixBoard.BoardWidth):
                shape = self.shapeAt(j, TetrixBoard.BoardHeight - i - 1)
                if shape != NoShape:
                    self.drawSquare(painter,
                            rect.left() + j * self.squareWidth(),
                            boardTop + i * self.squareHeight(), shape)

        if self.curPiece.shape() != 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 + (TetrixBoard.BoardHeight - y - 1) * self.squareHeight(),
                        self.curPiece.shape())

    def keyPressEvent(self, event):
        if not self.isStarted or self.isPaused or self.curPiece.shape() == NoShape:
            super(TetrixBoard, self).keyPressEvent(event)
            return

        key = event.key()
        if 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.rotatedRight(), self.curX, self.curY)
        elif key == Qt.Key_Up:
            self.tryMove(self.curPiece.rotatedLeft(), self.curX, self.curY)
        elif key == Qt.Key_Space:
            self.dropDown()
        elif key == Qt.Key_D:
            self.oneLineDown()
        else:
            super(TetrixBoard, self).keyPressEvent(event)

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            if self.isWaitingAfterLine:
                self.isWaitingAfterLine = False
                self.newPiece()
                self.timer.start(self.timeoutTime(), self)
            else:
                self.oneLineDown()
        else:
            super(TetrixBoard, self).timerEvent(event)

    def clearBoard(self):
        self.board = [NoShape for i in range(TetrixBoard.BoardHeight * TetrixBoard.BoardWidth)]

    def dropDown(self):
        dropHeight = 0
        newY = self.curY
        while newY > 0:
            if not self.tryMove(self.curPiece, self.curX, newY - 1):
                break
            newY -= 1
            dropHeight += 1

        self.pieceDropped(dropHeight)

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

    def pieceDropped(self, dropHeight):
        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.numPiecesDropped += 1
        if self.numPiecesDropped % 25 == 0:
            self.level += 1
            self.timer.start(self.timeoutTime(), self)
            self.levelChanged.emit(self.level)

        self.score += dropHeight + 7
        self.scoreChanged.emit(self.score)
        self.removeFullLines()

        if not self.isWaitingAfterLine:
            self.newPiece()

    def removeFullLines(self):
        numFullLines = 0

        for i in range(TetrixBoard.BoardHeight - 1, -1, -1):
            lineIsFull = True

            for j in range(TetrixBoard.BoardWidth):
                if self.shapeAt(j, i) == NoShape:
                    lineIsFull = False
                    break

            if lineIsFull:
                numFullLines += 1
                for k in range(TetrixBoard.BoardHeight - 1):
                    for j in range(TetrixBoard.BoardWidth):
                        self.setShapeAt(j, k, self.shapeAt(j, k + 1))

                for j in range(TetrixBoard.BoardWidth):
                    self.setShapeAt(j, TetrixBoard.BoardHeight - 1, NoShape)

        if numFullLines > 0:
            self.numLinesRemoved += numFullLines
            self.score += 10 * numFullLines
            self.linesRemovedChanged.emit(self.numLinesRemoved)
            self.scoreChanged.emit(self.score)

            self.timer.start(500, self)
            self.isWaitingAfterLine = True
            self.curPiece.setShape(NoShape)
            self.update()

    def newPiece(self):
        self.curPiece = copy.deepcopy(self.nextPiece)
        self.nextPiece.setRandomShape()
        self.showNextPiece()
        self.curX = TetrixBoard.BoardWidth // 2 + 1
        self.curY = TetrixBoard.BoardHeight - 1 + self.curPiece.minY()

        if not self.tryMove(self.curPiece, self.curX, self.curY):
            self.curPiece.setShape(NoShape)
            self.timer.stop()
            self.isStarted = False

    def showNextPiece(self):
        if self.nextPieceLabel is None:
            return

        dx = self.nextPiece.maxX() - self.nextPiece.minX() + 1
        dy = self.nextPiece.maxY() - self.nextPiece.minY() + 1

        pixmap = QPixmap(dx * self.squareWidth(), dy * self.squareHeight())
        painter = QPainter(pixmap)
        painter.fillRect(pixmap.rect(), self.nextPieceLabel.palette().window())

        for i in range(4):
            x = self.nextPiece.x(i) - self.nextPiece.minX()
            y = self.nextPiece.y(i) - self.nextPiece.minY()
            self.drawSquare(painter, x * self.squareWidth(),
                    y * self.squareHeight(), self.nextPiece.shape())

        painter.end()

        self.nextPieceLabel.setPixmap(pixmap)

    def tryMove(self, newPiece, newX, newY):
        for i in range(4):
            x = newX + newPiece.x(i)
            y = newY - newPiece.y(i)
            if x < 0 or x >= TetrixBoard.BoardWidth or y < 0 or y >= TetrixBoard.BoardHeight:
                return False
            if self.shapeAt(x, y) != NoShape:
                return False

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

    def drawSquare(self, painter, x, y, 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)
예제 #56
0
파일: front.py 프로젝트: siklee/mal_deep
class Form(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        self.setWindowTitle("Packing check")
        self.resize(640, 480)

        # 베이스 레이아웃
        layout_base = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.setLayout(layout_base)

        # 결과 출력을 QListView로 한다.
        grp_QListView = QGroupBox("결과 출력")
        layout = QBoxLayout(QBoxLayout.TopToBottom)

        self.listView = QListView(self)
        self.listView.setEditTriggers(QAbstractItemView.NoEditTriggers)

        layout.addWidget(self.listView)
        grp_QListView.setLayout(layout)

        # 프로그래스 바 레이아웃
        grp_QProgressBar = QGroupBox("진행도")
        grp_QProgressBar_layout = QBoxLayout(QBoxLayout.TopToBottom)

        self.pbar = QProgressBar(self)

        grp_QProgressBar_layout.addWidget(self.pbar)
        grp_QProgressBar.setLayout(grp_QProgressBar_layout)

        # 확인 버튼 누르면 QListView에 결과를 표시한다.
        self.confirm_btn = QPushButton("확인")

        layout_base.addWidget(grp_QListView)
        layout_base.addWidget(grp_QProgressBar)
        layout_base.addWidget(self.confirm_btn)

        self.progressTimer = QBasicTimer()
        # 프로그래스 바에 쓰는 타이머 인스턴스
        self.timerCounter = 1
        # 프로그래스 바 진행상황 표시에 사용할 변수

        self._PackingTest = PackingTest()
        # 패킹 테스트하는 인스턴스

        self.init_signals()
        self.show()

    def init_signals(self):
        self.confirm_btn.clicked.connect(self.on_click)

    @pyqtSlot()
    def on_click(self):

        DirectoryPath = self.selectDirectory()

        # UI의 X를 눌렀을때 None이 DirectoryPath에 들어가서 에러나기 때문에 추가한다.
        if len(DirectoryPath) == 0: return

        self.itemModel = QStandardItemModel()
        fileList = SearchFiles().travelingFolders(DirectoryPath)
        fileListLength = len(fileList)

        # 프로그래스 바 타이머 시작
        self.progressTimer.start(100, self)

        if fileListLength == 0:
            self.pbar.setValue(100)
            return

        start_time = time.time()

        # 패킹 파일을 검사한다.
        pathList = []
        packingTestResult = []
        packingTestResult = self._PackingTest.start(fileList, self.pbar,
                                                    self.timerCounter)

        print("--- %s seconds ---" % (time.time() - start_time))

        # paramiko에 적절한 path로 String을 고친다.
        for i in packingTestResult:
            # 파일 이름 얻기
            fullPath = i['packedFile']
            if fullPath == 'x':
                continue
                # 패킹 파일이 아니면 'x'가 들어있다. 'x'는 경로가 아니므로 무시한다.

            currentToken = re.search('\\\(\w*)', fullPath)
            nextStrIndex = 0

            # 폴더 선택하는 level에 따라서 backslash 개수가 달라진다. 예를 들어 하위 폴더가 2 level있는 폴더를 선택하면 backslash가 하위 경로에 2번 나타난다.
            while (currentToken is not None):
                if (nextStrIndex == 0):
                    nextStrIndex = currentToken.start() + 1
                    currentToken = re.search('\\\(\w*)',
                                             fullPath[nextStrIndex:])
                    nextStr = fullPath[nextStrIndex:]
                else:
                    nextStrIndex = currentToken.start() + 1
                    currentToken = re.search('\\\(\w*)',
                                             nextStr[nextStrIndex:])
                    nextStr = nextStr[nextStrIndex:]

            fileName = nextStr
            #             print(fileName);

            # full path 얻기
            fullPath = fullPath.replace('/', '\\').replace('\\', '\\\\')
            #             print(fullPath);

            # GUI에 출력하기
            rowString = str(i['entropies']) + ' <- ' + fullPath
            self.itemModel.appendRow(QStandardItem(rowString))

            pathInfo = {
                'fileName': fileName,
                'fullPath': fullPath
            }
            pathList.append(pathInfo)

        self.listView.setModel(self.itemModel)

        # SFTP를 사용해서 Sever로 파일 전송한다.
        #self.transferFilesToSever(pathList);

    # 디렉토리 선택창을 띄우고 선택한 디렉토리의 경로를 반환한다.
    def selectDirectory(self):
        dialog = QFileDialog()
        DirectoryPath = dialog.getExistingDirectory(None, "Select Folder")
        return DirectoryPath

    # 시간에 따른 프로그래스 바의 진행도를 측정하고 종료시키는 함수이다.
    def timerEvent(self, e):
        if self.timerCounter >= 100:
            self.progressTimer.stop()
            return

    # SFTP를 사용해서 Sever로 파일 전송한다.
    def transferFilesToSever(self, pathList):
        transport = paramiko.Transport(('IP', port))
        # IP 및 port 번호 공개하지 않도록 주의
        transport.connect(username='', password='')
        # 계정 및 비밀번호 공개하지 않도록 주의
        sftp = paramiko.SFTPClient.from_transport(transport)

        for i in pathList:
            uploadPath = '/경로/' + i['fileName']
            # 경로 공개하지 않도록 주의
            localpath = i['fullPath']

            sftp.put(localpath, uploadPath)

        sftp.close()
        transport.close()
예제 #57
0
class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # checkbox
        cb = QCheckBox('Show title', self)
        cb.move(20, 160)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)

        # toggle button
        self.col = QColor(0, 0, 0)
        redb = QPushButton('Red', self)
        redb.setCheckable(True)
        redb.move(10, 10)
        redb.clicked[bool].connect(self.setColor)
        redb = QPushButton('Green', self)
        redb.setCheckable(True)
        redb.move(10, 60)
        redb.clicked[bool].connect(self.setColor)
        blueb = QPushButton('Blue', self)
        blueb.setCheckable(True)
        blueb.move(10, 110)
        blueb.clicked[bool].connect(self.setColor)
        self.square = QFrame(self)
        self.square.setGeometry(150, 20, 100, 100)
        self.square.setStyleSheet("QWidget { background-color: %s }" %
                                  self.col.name())

        # slider
        sld = QSlider(Qt.Horizontal, self)
        sld.setFocusPolicy(Qt.NoFocus)
        sld.setGeometry(30, 210, 100, 30)
        sld.valueChanged[int].connect(self.changeValue)

        # pixmap
        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('web.png'))
        self.label.setGeometry(160, 210, 80, 30)

        # process bar
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 260, 200, 25)
        self.btn = QPushButton('Start', self)
        self.btn.move(40, 310)
        self.btn.clicked.connect(self.doAction)
        self.timer = QBasicTimer()
        self.step = 0

        # calendar
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.move(300, 10)
        cal.clicked[QDate].connect(self.showDate)
        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(300, 260)

        # line edit
        self.lbl2 = QLabel(self)
        qle = QLineEdit(self)
        qle.move(300, 310)
        self.lbl2.move(480, 310)
        qle.textChanged[str].connect(self.onChanged)

        self.setGeometry(300, 300, 640, 480)
        self.setWindowTitle('QCheckBox')
        self.show()

    def changeTitle(self, state):
        if state == Qt.Checked:
            self.setWindowTitle('QCheckBox')
        else:
            self.setWindowTitle('')

    def setColor(self, pressed):
        source = self.sender()
        if pressed:
            val = 255
        else:
            val = 0
        if source.text() == "Red":
            self.col.setRed(val)
        elif source.text() == "Green":
            self.col.setGreen(val)
        else:
            self.col.setBlue(val)
        self.square.setStyleSheet("QFrame { background-color: %s }" %
                                  self.col.name())

    def changeValue(self, value):
        if value == 0:
            self.label.setPixmap(QPixmap('web.png'))
        elif value > 0 and value <= 30:
            self.label.setPixmap(QPixmap('web.png'))
        elif value > 30 and value < 80:
            self.label.setPixmap(QPixmap('web.png'))
        else:
            self.label.setPixmap(QPixmap('web.png'))

    def timerEvent(self, e):
        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.btn.setText('Stop')

    def showDate(self, date):
        self.lbl.setText(date.toString())

    def onChanged(self, text):
        self.lbl2.setText(text)
        self.lbl2.adjustSize()
예제 #58
0
class ReversiWindow(QMainWindow):
    def __init__(self, board_size, game_mode, game_difficulty_level,
                 game_time_for_move):
        super().__init__()
        self.images = {}
        self.init_ui(board_size, game_mode, game_difficulty_level,
                     game_time_for_move)

    def init_ui(self, board_size, game_mode, game_difficulty_level,
                game_time_for_move):
        self.game = Game(board_size, mode=game_mode,
                         difficulty_level=game_difficulty_level,
                         is_console_game=False,
                         time_for_move=game_time_for_move)
        self.game_was_saved = False
        self.time_for_move = game_time_for_move
        self.count = self.time_for_move
        self.timer = QBasicTimer()
        self.move_timer = QTimer()
        self.ai_thread = AIThread(self)
        self.ai_thread.finished.connect(self.ai_finish)
        self.ai_finished = True
        self.load_images()
        self.add_toolbar()
        self.font_size = 10
        self.resize(board_size * s.IMG_SIZE,
                    (board_size * s.IMG_SIZE + self.toolbar.height() + 10 +
                     self.font_size))
        self.center()
        self.setWindowTitle('Reversi')
        self.show()
        self.timer.start(1, self)
        self.move_timer.timeout.connect(self.count_down)
        self.move_timer.start(1000)

    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)

    def add_toolbar(self):
        self.toolbar = self.addToolBar('')
        self.add_toolbar_action(self.toolbar, 'Save', 'save.png', self.save,
                                'Ctrl+S')
        self.add_toolbar_action(self.toolbar, 'Undo', 'undo.png', self.undo,
                                'Ctrl+Z')
        self.add_toolbar_action(self.toolbar, 'Redo', 'redo.png', self.redo)
        self.toolbar.setMovable(False)

    def add_toolbar_action(self, toolbar, name, image, function,
                           shortcut=None):
        action = QAction(QIcon(QPixmap(self.images[image])), name, self)
        if shortcut is not None:
            action.setShortcut(shortcut)
        action.triggered.connect(function)
        toolbar.addAction(action)

    def save(self):
        if self.game.game_state == Game.States.human:
            with open('saved_game.pickle', 'wb') as f:
                pickle.dump(self.game, f, protocol=pickle.HIGHEST_PROTOCOL)
            self.game_was_saved = True

    def undo(self):
        if self.game.game_state == Game.States.human:
            self.reset_count()
            self.game.undo()

    def redo(self):
        if self.game.game_state == Game.States.human:
            self.reset_count()
            self.game.redo()

    def draw_cell(self, painter, cell):
        if cell.state == s.BLACK:
            image = self.images['black.png']
        elif cell.state == s.WHITE:
            image = self.images['white.png']
        elif (cell.get_coordinates() in self.game.mover.next_possible_moves and
              self.game.game_state != Game.States.ai):
            image = self.images['possible_move.png']
        else:
            image = self.images['empty.png']
        painter.drawImage(
            cell.y*s.IMG_SIZE,
            cell.x*s.IMG_SIZE + self.toolbar.height() + self.font_size,
            image)

    def draw_text(self, painter, font_size):
        painter.setPen(QColor(Qt.black))
        painter.setFont(QFont('Decorative', font_size))
        painter.drawText(QPoint(10, self.toolbar.height() + font_size),
                         'Time left for move: {}'.format(self.count))

    def reset_count(self):
            if not self.ai_thread.isRunning():
                self.count = self.time_for_move

    def count_down(self):
        if self.count != 0:
            self.count -= 1
        else:
            if not self.ai_thread.isRunning():
                self.game.pass_move()
                self.reset_count()
                self.update()

    def ai_finish(self):
        self.update()
        self.reset_count()
        self.ai_finished = True

    def load_images(self):
        images_path = os.path.join(os.getcwd(), 'images')
        for image in os.listdir(images_path):
            self.images[image] = QImage(os.path.join(images_path, image))

    def mousePressEvent(self, QMouseEvent):
        if self.game.game_state == Game.States.human:
            position = QMouseEvent.pos()
            position.setY(
                position.y() - self.toolbar.height() - self.font_size)
            self.game.next_move(position)
            if self.game.game_state == Game.States.ai:
                self.reset_count()
            self.update()

    def timerEvent(self, event):
        if self.game.is_over():
            self.timer.stop()
            self.move_timer.stop()
            self.show_end_of_game_dialog()
        else:
            if self.game.game_state == Game.States.ai and self.ai_finished:
                self.ai_finished = False
                self.ai_thread.start()
        self.update()

    def paintEvent(self, event):
        with painter(self) as p:
            for cell in self.game.mover.board.cells():
                self.draw_cell(p, cell)
            self.draw_text(p, self.font_size)

    def show_end_of_game_dialog(self):
        message_box = QMessageBox()
        message_box.setText('The game is over! {}'.format
                            (self.game.get_winner_message()))
        message_box.exec_()
        if self.game_was_saved:
            self.ask_question(
                'Do you want to play from your last saved position?',
                message_box)
            self.check_answer(message_box.exec_(), self.load_saved_game,
                              self.play_again_action)
        else:
            self.play_again_action()

    def play_again_action(self):
        message_box = QMessageBox()
        message_box.setText('Do you want to play again?')
        self.ask_question('', message_box)
        self.check_answer(message_box.exec_(), self.restart,
                          self.close)

    def restart(self):
        self.game_was_saved = False
        self.game.restart()
        self.timer.start(1, self)
        self.move_timer.start(1000)

    def load_saved_game(self):
        with open('saved_game.pickle', 'rb') as f:
            self.game = pickle.load(f)
            self.timer.start(1, self)

    def ask_question(self, question, message_box):
        message_box.setInformativeText(question)
        message_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

    def check_answer(self, clicked_button, yes_action, no_action):
        if clicked_button == QMessageBox.Yes:
            yes_action()
        elif clicked_button == QMessageBox.No:
            no_action()
        self.update()
예제 #59
0
class Ui_ProyectoHCI(object):
    def openWindow(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.window)
        #ProyectoHCI.hide()
        self.window.show()

    def setupUi(self, ProyectoHCI):
        ProyectoHCI.setObjectName("ProyectoHCI")
        ProyectoHCI.resize(807, 554)
        font = QtGui.QFont()
        font.setPointSize(60)
        ProyectoHCI.setFont(font)
        ProyectoHCI.setStyleSheet(
            "border-image: url(:/backgroud/fondopantalla2.JPG);")

        # ------ Variables dentro de la Interfaz ------------------------------
        self.escritura = 0
        # ---------------------------------------------------------------------

        self.temp = 24
        self.tiempo = 0
        self.timer = QBasicTimer()
        self.step = 0
        self.time_left_int = DURATION_INT
        self.widget_counter_int = 0
        self.centralwidget = QtWidgets.QWidget(ProyectoHCI)
        self.centralwidget.setObjectName("centralwidget")
        self.debajotemperatura = QtWidgets.QPushButton(self.centralwidget)
        self.debajotemperatura.setGeometry(QtCore.QRect(80, 290, 91, 71))
        self.debajotemperatura.setStyleSheet(
            "image: url(:/backgroud/boton2.JPG);\n"
            "border-image: url(:/backgroud/boton2.JPG);")
        self.debajotemperatura.setText("")
        self.debajotemperatura.setObjectName("debajotemperatura")
        self.debajotemperatura.clicked.connect(self.on_click)
        self.abajotiempo = QtWidgets.QPushButton(self.centralwidget)
        self.abajotiempo.setGeometry(QtCore.QRect(360, 290, 91, 71))
        self.abajotiempo.setStyleSheet(
            "border-image: url(:/backgroud/boton2.JPG);")
        self.abajotiempo.setText("")
        self.abajotiempo.setObjectName("abajotiempo")
        self.abajotiempo.clicked.connect(self.on_click4)
        self.Encendido = QtWidgets.QPushButton(self.centralwidget)
        self.Encendido.setGeometry(QtCore.QRect(560, 150, 221, 91))
        self.Encendido.move(560, 150)
        self.Encendido.setStyleSheet(
            "border-image: url(:/backgroud/encendido.JPG);")
        self.Encendido.setText("")
        self.Encendido.setObjectName("Encendido")
        self.Encendido.clicked.connect(self.startchange)
        #self.Encendido.clicked.connect(self.doAction)
        #self.Encendido.clicked.connect(self.music)
        self.Pausa = QtWidgets.QPushButton(self.centralwidget)
        self.Pausa.setGeometry(QtCore.QRect(560, 150, 221, 91))
        self.Pausa.setStyleSheet("border-image: url(:/backgroud/pausa1.JPG);\n"
                                 "image: url(:/backgroud/pausa1.JPG);")
        self.Pausa.setText("")
        self.Pausa.setObjectName("Pausa")
        self.nada = QtWidgets.QPushButton(self.centralwidget)
        self.nada.setGeometry(QtCore.QRect(570, 50, 121, 71))
        self.nada.setStyleSheet("border-image: url(:/backgroud/blanck.JPG);")
        self.nada.setText("")
        self.nada.setObjectName("nada")
        self.grafica = QtWidgets.QPushButton(self.centralwidget)
        self.grafica.setGeometry(QtCore.QRect(560, 370, 221, 131))
        self.grafica.setStyleSheet(
            "border-image: url(:/backgroud/graficacaliente.JPG);")
        self.grafica.setText("")
        self.grafica.setObjectName("grafica")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(550, 120, 231, 251))
        self.pushButton_2.setStyleSheet(
            "border-image: url(:/backgroud/blanck.JPG);")
        self.pushButton_2.setText("")
        self.pushButton_2.setObjectName("pushButton_2")
        self.nada2 = QtWidgets.QPushButton(self.centralwidget)
        self.nada2.setGeometry(QtCore.QRect(30, 50, 181, 23))
        self.nada2.setStyleSheet("image: url(:/backgroud/blanck.JPG);\n"
                                 "border-image: url(:/backgroud/blanck.JPG);")
        self.nada2.setText("")
        self.nada2.setObjectName("nada2")
        self.nada3 = QtWidgets.QPushButton(self.centralwidget)
        self.nada3.setGeometry(QtCore.QRect(310, 50, 181, 23))
        self.nada3.setStyleSheet("border-image: url(:/backgroud/blanck.JPG);")
        self.nada3.setText("")
        self.nada3.setObjectName("nada3")
        self.help = QtWidgets.QPushButton(self.centralwidget)
        self.help.setGeometry(QtCore.QRect(700, 50, 81, 71))
        self.help.setStyleSheet("border-image: url(:/backgroud/help.JPG);")
        self.help.setText("")
        self.help.setObjectName("help")
        self.help.clicked.connect(self.openWindow)
        self.gradoactivo = QtWidgets.QPushButton(self.centralwidget)
        self.gradoactivo.setGeometry(QtCore.QRect(30, 140, 201, 151))
        self.gradoactivo.setStyleSheet(
            "border-image: url(:/backgroud/gradoactivo.JPG);")
        self.gradoactivo.setText("")
        self.gradoactivo.setObjectName("gradoactivo")
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(294, 142, 201, 151))
        self.pushButton_4.setStyleSheet(
            "border-image: url(:/backgroud/tiempoactivo.JPG);")
        self.pushButton_4.setText("")
        self.pushButton_4.setObjectName("pushButton_4")
        self.gradoalto = QtWidgets.QPushButton(self.centralwidget)
        self.gradoalto.setGeometry(QtCore.QRect(30, 140, 201, 151))
        self.gradoalto.setStyleSheet(
            "border-image: url(:/backgroud/gradospausa.JPG);")
        self.gradoalto.setText("")
        self.gradoalto.setObjectName("gradoalto")
        self.tiempopausa = QtWidgets.QPushButton(self.centralwidget)
        self.tiempopausa.setGeometry(QtCore.QRect(290, 140, 211, 151))
        self.tiempopausa.setStyleSheet(
            "border-image: url(:/backgroud/tiempopausa.JPG);")
        self.tiempopausa.setText("")
        self.tiempopausa.setObjectName("tiempopausa")
        self.gradoinactivo = QtWidgets.QPushButton(self.centralwidget)
        self.gradoinactivo.setGeometry(QtCore.QRect(30, 140, 201, 151))
        self.gradoinactivo.setStyleSheet(
            "border-image: url(:/backgroud/gradorun.JPG);")
        self.gradoinactivo.setText("")
        self.gradoinactivo.setObjectName("gradoinactivo")
        self.tiemporun = QtWidgets.QPushButton(self.centralwidget)
        self.tiemporun.setGeometry(QtCore.QRect(290, 140, 211, 151))
        self.tiemporun.setStyleSheet(
            "border-image: url(:/backgroud/tiemporun.JPG);")
        self.tiemporun.setText("")
        self.tiemporun.setObjectName("tiemporun")
        self.lcdNumber = QtWidgets.QLCDNumber(self.centralwidget)
        self.lcdNumber.setGeometry(QtCore.QRect(50, 170, 121, 81))
        self.lcdNumber.setStyleSheet(
            "border-image: url(:/backgroud/blanck.JPG);\n"
            "font: 36pt \"MS Shell Dlg 2\";")
        self.lcdNumber.setObjectName("lcdNumber")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(170, 170, 31, 31))
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(22)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.label.setFont(font)
        self.label.setStyleSheet("border-image: url(:/backgroud/blanck.JPG);\n"
                                 "font: 8pt \"Copperplate Gothic Light\";\n"
                                 "font: 8pt \"MS Shell Dlg 2\";\n"
                                 "font: 8pt \"Century Gothic\";\n"
                                 "font: 75 22pt \"MS Shell Dlg 2\";")
        self.label.setObjectName("label")
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setGeometry(QtCore.QRect(170, 200, 31, 51))
        self.pushButton_5.setStyleSheet(
            "border-image: url(:/backgroud/blanck.JPG);")
        self.pushButton_5.setText("")
        self.pushButton_5.setObjectName("pushButton_5")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(310, 170, 171, 81))
        font = QtGui.QFont()
        font.setPointSize(22)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet(
            "border-image: url(:/backgroud/blanck.JPG);")
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")
        #LCD Number 2
        self.timenumber = QtWidgets.QLCDNumber(self.centralwidget)
        self.timenumber.setGeometry(QtCore.QRect(310, 170, 121, 81))
        self.timenumber.setStyleSheet(
            "border-image: url(:/backgroud/blanck.JPG);\n"
            "font: 36pt \"MS Shell Dlg 2\";")
        self.timenumber.setObjectName("lcdNumber2")
        #self.timer.clicked.connect(self._update)
        #self.timer = QTimer()
        #self.timer.timeout.connect(self._update)
        #self.timer.start(1000)
        #end lcd number 2
        self.temperaturadeseada = QtWidgets.QPushButton(self.centralwidget)
        self.temperaturadeseada.setGeometry(QtCore.QRect(0, 370, 257, 181))
        self.temperaturadeseada.setStyleSheet(
            "border-image: url(:/backgroud/temperaturadeseada.JPG);")
        self.temperaturadeseada.setText("")
        self.temperaturadeseada.setObjectName("temperaturadeseada")
        self.nadass = QtWidgets.QPushButton(self.centralwidget)
        self.nadass.setGeometry(QtCore.QRect(0, 370, 257, 184))
        self.nadass.setStyleSheet("border-image: url(:/backgroud/blanck.JPG);")
        self.nadass.setText("")
        self.nadass.setObjectName("nadass")
        self.subirtemperatura = QtWidgets.QPushButton(self.centralwidget)
        self.subirtemperatura.setGeometry(QtCore.QRect(80, 70, 91, 71))
        self.subirtemperatura.setStyleSheet(
            "border-image: url(:/backgroud/botondearriba.JPG);")
        self.subirtemperatura.setText("")
        self.subirtemperatura.setObjectName("subirtemperatura")
        self.subirtemperatura.clicked.connect(self.on_click2)

        self.arribatiempo = QtWidgets.QPushButton(self.centralwidget)
        self.arribatiempo.setGeometry(QtCore.QRect(360, 70, 91, 71))
        self.arribatiempo.setStyleSheet(
            "border-image: url(:/backgroud/botondearriba.JPG);")
        self.arribatiempo.setText("")
        self.arribatiempo.setObjectName("arribatiempo")
        self.arribatiempo.clicked.connect(self.on_click3)
        self.oktemperatura = QtWidgets.QPushButton(self.centralwidget)
        self.oktemperatura.setGeometry(QtCore.QRect(70, 500, 111, 41))
        self.oktemperatura.setStyleSheet(
            "border-image: url(:/backgroud/ok.JPG);")
        self.oktemperatura.setText("")
        self.oktemperatura.setObjectName("oktemperatura")
        self.temperaturacargando = QtWidgets.QPushButton(self.centralwidget)
        self.temperaturacargando.setGeometry(QtCore.QRect(0, 370, 257, 184))
        self.temperaturacargando.setStyleSheet(
            "border-image: url(:/backgroud/cargandotemperaturafinal.JPG);")
        self.temperaturacargando.setText("")
        self.temperaturacargando.setObjectName("temperaturacargando")
        self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QtCore.QRect(20, 460, 211, 31))
        self.progressBar.setStyleSheet(
            "background-image: url(:/backgroud/blanck.JPG);\n"
            "border-image: url(:/backgroud/blanck.JPG);\n"
            "image: url(:/backgroud/blanck.JPG);")
        self.progressBar.setProperty("value", 24)
        self.progressBar.setObjectName("progressBar")
        #timer
        #self.timer2 = QBasicTimer()
        #self.step = 0
        #end timer
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(720, 120, 47, 13))
        self.label_3.setStyleSheet(
            "border-image: url(:/backgroud/blanck.JPG);")
        self.label_3.setObjectName("label_3")
        self.nuevaconsulta = QtWidgets.QPushButton(self.centralwidget)
        self.nuevaconsulta.setGeometry(QtCore.QRect(560, 250, 221, 91))
        self.nuevaconsulta.setStyleSheet(
            "border-image: url(:/backgroud/nuevaconsulta2.JPG);")
        self.nuevaconsulta.setText("")
        self.nuevaconsulta.setObjectName("nuevaconsulta")
        self.nuevaconsulta.clicked.connect(self.nuevac)

        self.oktemperatura_2 = QtWidgets.QPushButton(self.centralwidget)
        self.oktemperatura_2.setGeometry(QtCore.QRect(70, 500, 111, 41))
        self.oktemperatura_2.setStyleSheet(
            "border-image: url(:/backgroud/ok.JPG);")
        self.oktemperatura_2.setText("")
        self.oktemperatura_2.setObjectName("oktemperatura_2")
        self.pushButton_2.raise_()
        self.debajotemperatura.raise_()
        self.abajotiempo.raise_()
        self.Pausa.raise_()
        #self.QBasicTimer.raise_()
        self.nada.raise_()
        self.grafica.raise_()
        self.Encendido.raise_()
        self.nada2.raise_()
        self.nada3.raise_()
        self.help.raise_()
        self.gradoactivo.raise_()
        self.pushButton_4.raise_()
        self.gradoalto.raise_()
        self.tiempopausa.raise_()
        self.gradoinactivo.raise_()
        self.tiemporun.raise_()
        self.lcdNumber.raise_()
        self.label.raise_()
        self.pushButton_5.raise_()
        self.label_2.raise_()
        self.nadass.raise_()
        #self.temperaturadeseada.raise_()
        self.subirtemperatura.raise_()
        self.arribatiempo.raise_()
        #self.oktemperatura.raise_()
        #self.temperaturacargando.raise_()
        #self.progressBar.raise_()
        self.label_3.raise_()
        self.nuevaconsulta.raise_()
        #self.oktemperatura_2.raise_()
        self.timenumber.raise_()
        #self.QTimer.raise_()
        ProyectoHCI.setCentralWidget(self.centralwidget)

        self.retranslateUi(ProyectoHCI)
        QtCore.QMetaObject.connectSlotsByName(ProyectoHCI)

    def retranslateUi(self, ProyectoHCI):
        _translate = QtCore.QCoreApplication.translate
        ProyectoHCI.setWindowTitle(_translate("ProyectoHCI", "OCCHIO VARMO"))
        self.label.setText(_translate("ProyectoHCI", "℃"))
        self.label_3.setText(_translate("ProyectoHCI", "  Ayuda"))

    def on_click(self):
        self.temp = self.temp - 1
        self.lcdNumber.display(self.temp)
        self.escritura = self.temp + 40
        ser.write(bytes([self.escritura]))
        print(self.escritura)

    def on_click2(self):
        self.temp = self.temp + 1
        self.lcdNumber.display(self.temp)
        self.escritura = self.temp + 40
        ser.write(bytes([self.escritura]))
        print(self.escritura)

    def on_click3(self):
        self.tiempo = self.tiempo + 1
        self.timenumber.display(self.tiempo)

    def on_click4(self):
        self.tiempo = self.tiempo - 1
        self.timenumber.display(self.tiempo)

    #def _update(self):
    #   """Update display each """
    #   time = QTime.currentTime().toString()
    #  self.display(time)

    def startchange(self):
        self.gradoinactivo.lower()
        self.tiemporun.lower()
        self.temperaturacargando.raise_()
        self.progressBar.raise_()
        self.oktemperatura.raise_()
        self.oktemperatura_2.raise_()
        gui2 = QLCDCountDown(None, None,
                             datetime.strptime('Jun 2020', '%b %Y'))
        gui2.show()

    def nuevac(self):
        self.gradoinactivo.raise_()
        self.tiemporun.raise_()
        self.temperaturacargando.lower()
        self.progressBar.lower()
        self.oktemperatura.lower()
        self.oktemperatura_2.lower()
        self.pushButton_5.raise_()
        self.lcdNumber.raise_()
        self.label.raise_()
        self.label_2.raise_()
        self.timenumber.raise_()
        self.tiempo = self.tiempo = 0
        self.temp = self.temp = 0
        self.timenumber.display(self.tiempo)
        self.lcdNumber.display(self.temp)

    def timerEvent(self, e):

        if self.step >= 100:

            self.timer.stop()
            self.Encendido.setText('Finished')
            return

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

    def doAction(self):

        if self.timer.isActive():
            self.timer.stop()
            self.Encendido.setText('Start')
        else:
            #self.timer.start(self, 100, QBasicTimer)
            self.timer.start(self, 100, QBasicTimer, ProyectoHCI)

            self.Encendido.setText('Stop')

    def music(self):
        app = QtCore.QCoreApplication(sys.argv)
        url = QtCore.QUrl.fromLocalFile("./fairydust.mp3")
        content = M.QMediaContent(url)
        player = M.QMediaPlayer()
        player.setMedia(content)
        player.play()
예제 #60
0
class GUI(QMainWindow):
    def __init__(self):
        super().__init__()
        #self.welcomeUI()
        self.connect_to_socket()
        self.initUI()

    def initUI(self):
        self.setGeometry(50, 50, 600, 600)
        self.setWindowTitle('Bomberman')
        self.timer = QBasicTimer()
        self.timer.start(20, self)
        self.__player = next(
            filter(lambda player: player.id == 2, self.__game.players), None)
        self.bombs = []
        self.label_bombs = []
        self.labels_for_bombs = [QLabel(self) for i in range(200)]
        for label in self.labels_for_bombs:
            label.setPixmap(QPixmap('bomb1.jpg'))
            label.setGeometry(50, 50, 0, 0)
        self.label_players = [[QLabel(self), player]
                              for player in self.__game.players]
        for label in self.label_players:
            label[0].setPixmap(QPixmap('player1.jpg'))
        self.label_blocks1 = [[QLabel(self), block]
                              for block in self.__game.blocks
                              if not block.destroyable]
        for label in self.label_blocks1:
            label[0].setPixmap(QPixmap('block1.jpg'))
            label[0].setGeometry(
                QRect(15 * label[1].x, 15 * label[1].y, 15, 15))
        self.label_blocks2 = [[QLabel(self), block]
                              for block in self.__game.blocks
                              if block.destroyable]
        for label in self.label_blocks2:
            label[0].setPixmap(QPixmap('block2.jpg'))
            label[0].setGeometry(
                QRect(15 * label[1].x, 15 * label[1].y, 15, 15))
        self.show()

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            self.repaint()
        else:
            super.timerEvent(event)

    def paintEvent(self, *args, **kwargs):
        try:
            new_bombs = set(self.__game.bombs).difference(set(self.bombs))
            if len(new_bombs) > 0:
                self.bombs.extend(list(new_bombs))
                for bomb in new_bombs:
                    self.label_bombs.append(
                        [self.labels_for_bombs.pop(), bomb])

            for label in self.label_players + self.label_bombs:
                #if isinstance(label[1], Player): print(label[1])
                if label[1].alive:
                    label[0].setGeometry(
                        QRect(15 * label[1].x, 15 * label[1].y, 15, 15))
                else:
                    label[0].hide()

            for label in self.label_blocks2:
                if not label[1].alive:
                    label[0].hide()
        except:
            pass

    def keyPressEvent(self, e):
        if self.__player.alive and not e.isAutoRepeat():
            if e.key() == Qt.Key_Space:
                bomb = self.__player.place_bomb()
                self.__game.bomb_it(bomb)
                self.send(bomb)
                return
            if e.key() == Qt.Key_W:
                self.__player.move('Up', self.__game)
            if e.key() == Qt.Key_S:
                self.__player.move('Down', self.__game)
            if e.key() == Qt.Key_A:
                self.__player.move('Left', self.__game)
            if e.key() == Qt.Key_D:
                self.__player.move('Right', self.__game)
            self.send(self.__player)

        if e.key() == Qt.Key_Escape:
            self.close()
        if e.key() == Qt.Key_Q:
            print(self.__player)

    def recieve(self, socket):
        while True:
            resp = socket.recv(128).decode('utf-8')
            if resp != '':
                game_object = parse(resp)
                if isinstance(game_object, Player):
                    self.__game.players[int(game_object.id) - 1].x = (int(
                        game_object.x))
                    self.__game.players[int(game_object.id) - 1].y = (int(
                        game_object.y))
                    self.label_players[int(game_object.id) -
                                       1][1] = game_object
                else:
                    self.__game.bomb_it(game_object)

    def send(self, game_object):
        self.clientsocket.send(str(game_object).encode('utf-8'))

    def create_socket(self):
        self.__game = Game()
        serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        serversocket.bind((socket.gethostname(), 8080))
        serversocket.listen(5)
        # while True:
        (self.clientsocket, address) = serversocket.accept()
        print("hi ", address)
        self.clientsocket.send(jsonpickle.encode(self.__game).encode('utf-8'))
        threading.Thread(target=self.recieve,
                         args=(self.clientsocket, )).start()

    def connect_to_socket(self):
        self.clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.clientsocket.connect(('Czarek', 8080))
        resp = self.clientsocket.recv(60720).decode('utf-8')
        game = jsonpickle.decode(resp)
        self.__game = game
        threading.Thread(target=self.recieve,
                         args=(self.clientsocket, )).start()