Exemplo n.º 1
0
    def initUI(self):
        self.labelUsername = QLabel(self)
        self.labelUsername.setText("Username")
        self.labelPassword = QLabel(self)
        self.labelPassword.setText("Password")
        self.labelRole = QLabel(self)
        self.labelRole.setText("Role")
        self.labelUsername.move(250, 100)
        self.labelPassword.move(250, 130)
        self.labelRole.move(250, 160)
        self.username = QLineEdit(self)
        self.username.move(300, 100)
        self.password = QLineEdit(self)
        self.password.setEchoMode(QLineEdit.Password)
        self.password.move(300, 130)
        self.role = QComboBox(self)
        self.role.addItem("Student")
        self.role.addItem("Librarian")
        self.role.addItem("Admin")
        self.role.move(300, 160)

        button = QPushButton("Add User", self)
        button.move(300, 190)
        button.clicked.connect(self.add_user)

        self.setWindowTitle("Add Users")
        self.setGeometry(self.left, self.top, self.width, self.height)
Exemplo n.º 2
0
class IssueBook(QWidget):
    session = Session()

    def __init__(self):
        super().__init__()
        self.title = "Admin Panel"
        self.width = 640
        self.height = 400
        self.top = 100
        self.left = 100
        self.initUI()

    def initUI(self):

        self.lblIssuedTo = QLabel(self)
        self.lblIssuedTo.setText("Issued To")
        self.lblIssuedTo.move(180, 100)

        self.lblBook = QLabel(self)
        self.lblBook.setText("Book")
        self.lblBook.move(180, 130)

        self.issuedTo = QComboBox(self)
        self.issuedTo.move(220, 100)
        self.populateUsers(self.issuedTo)

        self.Book = QComboBox(self)
        self.Book.move(220, 130)
        self.populateBooks(self.Book)

        self.saveBtn = QPushButton("Issue Book", self)
        self.saveBtn.move(250, 200)
        self.saveBtn.clicked.connect(self.saveIssue)

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()

    def populateUsers(self, combobox):
        users = self.session.query(User).filter(User.role == "Student")
        for user in users:
            combobox.addItem(user.username)

    def populateBooks(self, combobox):
        books = self.session.query(Book).all()
        for book in books:
            combobox.addItem(book.name)

    def saveIssue(self):
        issued_to = self.session.query(User).filter(
            User.username == self.issuedTo.currentText()).first()
        book = self.session.query(Book).filter(
            Book.name == self.Book.currentText()).first()
        try:
            issued = Issue(issued_to.id, book.id)
            self.session.add(issued)
            self.session.commit()
        except:
            print("An error occured")
Exemplo n.º 3
0
 def npkBtn(self):
     npkBtn_ = QPushButton(self)
     npkBtn_.resize(60, 25)
     npkBtn_.move(0, self.height() - self.btnHeight * 1)
     npkBtn_.setObjectName("_npkFuncBtn_")
     npkBtn_.setText("功能")
     npkBtn_.setEnabled(False)
     return npkBtn_
Exemplo n.º 4
0
    def initUi(self):
        self.setGeometry(600, 300, 400, 200)
        self.setWindowTitle('Absolute Positioning')

        #QPushButton
        btn = QPushButton('Button', self)
        btn.resize(btn.sizeHint())
        btn.move(150, 100)
Exemplo n.º 5
0
 def positional_layout(self):
     print(self.menuBar().size())
     menbar_height = self.menuBar().height()
     print(menbar_height)
     label = QLabel('Our first Widget',self)
     label.resize(120,30)
     label.move(10,menbar_height)
     button = QPushButton('Click',self)
     button.move(label.width() + 25,label.height())
Exemplo n.º 6
0
 def checkBox(self):
     #
     confirmBtn = QPushButton("确认", self)
     confirmBtn.resize(self.width() // 2, 25)
     confirmBtn.move(0, self.height() - 25)
     confirmBtn.clicked.connect(self.hide)
     #
     cancelBtn = QPushButton("取消", self)
     cancelBtn.resize(self.width() // 2, 25)
     cancelBtn.move(self.width() // 2, self.height() - 25)
     cancelBtn.clicked.connect(self.close)
Exemplo n.º 7
0
    def saveDirSelectBtn(self):
        btn = QPushButton("保存文件夹", self)
        btn.setObjectName("saveDirSelectBtn")
        btn.resize(self.width() / 2, self.height_)
        btn.move(0, self.height_ * 2)

        # btn.setStyleSheet("background-color: pink")

        def btnFunc():
            saveDirFunc(self)

        btn.clicked.connect(btnFunc)
Exemplo n.º 8
0
    def newNpkDictBtn(self):
        newNpkBtn_ = QPushButton(self)
        newNpkBtn_.resize(60, 25)
        newNpkBtn_.move(0, self.height() - self.btnHeight * 2)
        newNpkBtn_.setText("新建")

        def newBtnFunc():
            result = newDictBtnFunc(self)

        newNpkBtn_.clicked.connect(newBtnFunc)

        return newNpkBtn_
Exemplo n.º 9
0
class Interface(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(150, 150, 529, 498)
        self.setWindowTitle('Рисование КРУГА')

        self.pushButton = QPushButton("Нарисовать круг", self)
        self.pushButton.resize(511, 31)
        self.pushButton.move(10, 20)
Exemplo n.º 10
0
    def testPortBtn(self):
        portBtn = QPushButton("默认端口测试", self)
        portBtn.setObjectName("testPortBtn")
        portBtn.resize((self.width() - 30) / 2, self.height_)
        portBtn.move(0, self.height_ * 3)

        # portBtn.setEnabled(False)

        def portBtnFunc():
            testPortFunc(self)

        portBtn.clicked.connect(portBtnFunc)
        return portBtn
Exemplo n.º 11
0
class editpopup(QWidget):
    user_id = ""
    session = Session()

    def __init__(self):
        super().__init__()
        self.title = "Edit Pop Up"
        self.width = 500
        self.height = 500
        self.top = 100
        self.left = 100
        self.initUI()

    def initUI(self):
        self.username = QLineEdit(self)
        self.username.move(200, 200)

        self.password = QLineEdit(self)
        self.password.move(200, 240)
        self.password.setEchoMode(QLineEdit.Password)

        self.role = QComboBox(self)
        self.role.addItem("Student")
        self.role.addItem("Librarian")
        self.role.addItem("Admin")
        self.role.move(200, 280)

        self.savechanges = QPushButton("Save changes", self)
        self.savechanges.move(250, 350)
        self.savechanges.clicked.connect(self.updateValues)
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

    def setValues(self, user_id, user_name, user_password, user_role):
        self.user_id = user_id
        self.username.setText(user_name)
        self.password.setText(user_password)
        self.role.setCurrentText(user_role)

    def updateValues(self):
        result = self.session.query(User).filter(
            User.id == self.user_id).first()
        result.username = self.username.text()
        result.password = self.password.text()
        result.role = self.role.currentText()
        try:
            self.session.add(result)
            self.session.commit()
            self.close()
        except:
            print("Error occured while saving")
Exemplo n.º 12
0
    def img2DirBtn(self):
        btn = QPushButton("ImagePacks2文件夹", self)
        btn.setObjectName("saveDirSelectBtn")
        btn.resize(self.width() / 2, self.height_)
        btn.move(self.width() / 2, self.height_ * 2)

        # btn.setStyleSheet("background-color: pink")

        def btnFunc():
            if img2DirFunc(self) is False:
                QMessageBox.warning(self, "img2文件夹选择错误", "文件夹下无NPK文件,请重新选择",
                                    QMessageBox.Yes, QMessageBox.Yes)

        btn.clicked.connect(btnFunc)
Exemplo n.º 13
0
    def readNpkDictBtn(self):
        readNpkBtn_ = QPushButton(self)
        readNpkBtn_.resize(60, 25)
        readNpkBtn_.move(0, self.height() - self.btnHeight * 3)
        readNpkBtn_.setText("读取")

        def readDict():
            result = readDictFile(self)
            if result:
                self.mainWin.findChild(QPushButton,
                                       "_npkFuncBtn_").setEnabled(True)

        readNpkBtn_.clicked.connect(readDict)
        return readNpkBtn_
Exemplo n.º 14
0
class Login(QWidget):
    session = Session()

    def __init__(self):
        super().__init__()
        self.title = "Admin Panel"
        self.width = 640
        self.height = 400
        self.top = 100
        self.left = 100
        self.adminPanelUI = AdminPanel()
        self.initUI()

    def initUI(self):
        self.lblusername = QLabel(self)
        self.lblpassword = QLabel(self)
        self.lblusername.move(200, 100)
        self.lblusername.setText("USERNAME")
        self.lblpassword.move(200, 140)
        self.lblpassword.setText("PASSWORD")
        self.username = QLineEdit(self)
        self.username.move(250, 100)

        self.password = QLineEdit(self)
        self.password.move(250, 140)
        self.password.setEchoMode(QLineEdit.Password)

        self.login = QPushButton("Login", self)
        self.login.move(280, 300)

        self.login.clicked.connect(self.onclick)

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()

    def onclick(self):
        user = self.session.query(User).filter(
            User.username == self.username.text()).first()
        print("User Exists")
        if (user.password == self.password.text()):
            role = user.role
            print(role)
            if (role == "Student"):
                print("It is a student")
            elif (role == "Librarian"):
                print("Redirect to the librarian UI")
            else:
                self.adminPanelUI.show()
Exemplo n.º 15
0
    def position_widget_layout(self):
        label_1 = QLabel('Our first label', self)  # create and set the label

        print(self.menuBar().size())  # siza default 100, 30
        mbar_height = self.menuBar().height()
        print(mbar_height)
        label_1.move(10, mbar_height)  # move the label in the window

        label_2 = QLabel('Another label', self)
        label_2.move(10, mbar_height * 2)

        button_1 = QPushButton('Click 1', self)
        button_2 = QPushButton('Click 2', self)

        button_1.move(label_1.width(), label_1.height())
        button_2.move(label_2.width(), label_2.height() * 2)
Exemplo n.º 16
0
    def iniUi(self):

        self.roi = QLabel(self)
        self.roi.resize(400, 400)
        self.roi.move(25, 25)
        startButton = QPushButton('Correct Roi', self)
        startButton.resize(100, 50)
        startButton.move(450, 25)
        #self.setPlayersNum.activated[str].connect(self.Activation)
        cancelButton = QPushButton('Done', self)
        cancelButton.resize(100, 50)
        cancelButton.move(450, 100)

        self.setGeometry(300, 300, 550, 500)
        self.setWindowTitle('Roi Correction')
        self.show()
    def positional_widget_layout(self):
        label_1 = QLabel('Our first label', self)

        print(
            self.menuBar().size())  # default size: PyQt5.QtCore.QSize(100, 30)
        mbar_height = self.menuBar().height()
        print(mbar_height)
        label_1.move(10, mbar_height)  # position label below menubar

        label_2 = QLabel('Another label', self)  # create another label
        label_2.move(10, mbar_height * 2)  # align and position below label_1

        button_1 = QPushButton('click 1', self)
        button_2 = QPushButton('click 2', self)

        button_1.move(label_1.width(), label_1.height())
        button_2.move(label_1.width(), label_1.height() * 2)
Exemplo n.º 18
0
 def initUI(self):
         self.labelBookName = QLabel(self)
         self.labelBookName.setText("Book Name")
         self.labelAuthor = QLabel(self)
         self.labelAuthor.setText("Author")
         self.labelBookName.move(250, 100)
         self.labelAuthor.move(250, 130)
         
         self.bookname = QLineEdit(self)
         self.bookname.move(300, 100)
         self.author = QLineEdit(self)
         self.author.move(300, 130)
         button = QPushButton("Add Book", self)
         button.move(300, 190)
         button.clicked.connect(self.add_book)
        
         self.setWindowTitle("Add Books")
         self.setGeometry(self.left, self.top, self.width, self.height)
Exemplo n.º 19
0
    def initUi(self):
        self.setGeometry(50, 50, 1024, 600)
        self.setObjectName('MainWindow')
        self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint)

        exitButton = QPushButton('Exit', self)
        exitButton.setObjectName("ExitButton")
        exitButton.resize(EXIT_BUTTON_WIDTH, EXIT_BUTTON_HEIGHT)
        exitButton.move(EXIT_BUTTON_X, EXIT_BUTTON_Y)
        exitButton.clicked.connect(QCoreApplication.instance().quit)

        self.createMainControls()

        self.createStatusBar()

        self.createMiscControls()

        self.show()
Exemplo n.º 20
0
    def initUI(self):
        self.resize(400, 180)
        self.setWindowTitle("Ticket Analysis")
        self.setWindowIcon(QIcon('Keyword_Analysis'))

        CsvUploadBtn = QPushButton("CSV Upload", self)
        CsvUploadBtn.resize(CsvUploadBtn.sizeHint())
        CsvUploadBtn.clicked.connect(self.Browse)
        CsvUploadBtn.move(10, 10)

        self.FilePathLbl = QLabel(self)
        self.FilePathLbl.move(100, 15)

        AnalyseBtn = QPushButton("Analyse", self)
        AnalyseBtn.move(10, 40)
        AnalyseBtn.clicked.connect(self.Analyse)

        self.ProgressBar = QProgressBar(self)
        self.ProgressBar.move(100, 41)
        self.ProgressBar.hide()
        self.ProgressBar.setProperty("value", 1)
        self.ProgressBar.setMinimumWidth(300)

        ConfirmationLbl = QLabel("Ticket analysis done", self)
        ConfirmationLbl.move(10, 110)

        ConfirmationLbl2 = QLabel("Please check the folder in the directory",
                                  self)
        ConfirmationLbl2.move(10, 130)

        OpenDirectory = QPushButton("Open Directory", self)
        OpenDirectory.move(285, 125)
        OpenDirectory.clicked.connect(self.OpenDir)

        self.show()
Exemplo n.º 21
0
class editpopup(QWidget):
    book_id=""
    session=Session()
    def __init__(self):
        super().__init__()
        self.title="Edit Pop Up"
        self.width = 500
        self.height = 500
        self.top = 100
        self.left = 100
        self.initUI()
    def initUI(self):
        self.bookname=QLineEdit(self)
        self.bookname.move(200,200)
        
        self.author=QLineEdit(self)
        self.author.move(200,240)
        
        self.savechanges=QPushButton("Save changes",self)
        self.savechanges.move(250,300)
        self.savechanges.clicked.connect(self.updateValues)
        self.setWindowTitle(self.title)
        self.setGeometry(self.left,self.top,self.width,self.height)
        
    def setValues(self,book_id,book_name,book_author):
           self.book_id=book_id
           self.bookname.setText(book_name)
           self.author.setText(book_author)
           
    def updateValues(self):
        result=self.session.query(Book).filter(Book.id==self.book_id).first()
        result.name=self.bookname.text()
        result.author=self.author.text()
        try:
            self.session.add(result)
            self.session.commit()
            self.close()
        except:
            print("Error occured while saving")
Exemplo n.º 22
0
class MyWin(QWidget):
    def __init__(self):
        super().__init__()
        # 按钮初始化
        self.btn_1 = QPushButton('按钮1', self)
        self.btn_1.move(120, 80)
        self.btn_1.clicked.connect(self.click_1)  # 绑定槽函数

        self.btn_2 = QPushButton('按钮2', self)
        self.btn_2.move(120, 120)
        self.btn_2.clicked.connect(self.click_2)  # 绑定槽函数

    def click_1(self):
        self.thread_1 = Thread_1()  # 创建线程
        self.thread_1.start()  # 开始线程

    def click_2(self):
        self.btn_2.setEnabled(False)
        self.thread_2 = Thread_2()
        self.thread_2._signal.connect(self.set_btn)
        self.thread_2.start()

    def set_btn(self):
        self.btn_2.setEnabled(True)
Exemplo n.º 23
0
    def createMainControls(self):
        radioButton = QPushButton('FM Radio', self)
        radioButton.resize(MAIN_CONTROLS_WIDTH, MAIN_CONTROLS_HEIGHT)
        radioButton.move(MAIN_CONTROLS_X_START, MAIN_CONTROLS_Y)
        radioButton.clicked.connect(lambda: MainController.getInstance().
                                    changeState(MainController.STATE_FM))

        auxButton = QPushButton('AUX', self)
        auxButton.resize(MAIN_CONTROLS_WIDTH, MAIN_CONTROLS_HEIGHT)
        auxButton.move(
            MAIN_CONTROLS_X_START + MAIN_CONTROLS_WIDTH +
            MAIN_CONTROLS_DISTANCE, MAIN_CONTROLS_Y)
        auxButton.clicked.connect(lambda: MainController.getInstance().
                                  changeState(MainController.STATE_AUX))

        mediaButton = QPushButton('Media', self)
        mediaButton.resize(MAIN_CONTROLS_WIDTH, MAIN_CONTROLS_HEIGHT)
        mediaButton.move(
            MAIN_CONTROLS_X_START + 2 *
            (MAIN_CONTROLS_WIDTH + MAIN_CONTROLS_DISTANCE), MAIN_CONTROLS_Y)
        mediaButton.clicked.connect(lambda: MainController.getInstance().
                                    changeState(MainController.STATE_MEDIA))
 def initUI(self):
     self.resize(454, 34)
     self.setFrameStyle(QFrame.StyledPanel)
     self.setLineWidth(1)
     
     button_stylesheet = """
                             .QPushButton {
                                 font-weight: bold;
                                 font-size: 13px;
                                 background-color:#E0E0E0;
                             }                                
                         """
     
     """ all the control button switches are created from here """               
     world_tools_button = QPushButton('World Tools', self)
     world_tools_button.setCheckable(True)
     world_tools_button.resize(150, 30)
     world_tools_button.move(2, 2)        
     world_tools_button.setStyleSheet(button_stylesheet)
     world_tools_button.clicked.connect(self.pressControlPanelButton)
     
     stickman_tools_button = QPushButton('Stickman Tools', self)
     stickman_tools_button.setCheckable(True)
     stickman_tools_button.resize(150, 30)
     stickman_tools_button.move(152, 2)
     stickman_tools_button.setStyleSheet(button_stylesheet)
     stickman_tools_button.clicked.connect(self.pressControlPanelButton)
     
     animation_tools_button = QPushButton('Animation Tools', self)
     animation_tools_button.setCheckable(True)
     animation_tools_button.resize(150, 30)
     animation_tools_button.move(302, 2)
     animation_tools_button.setStyleSheet(button_stylesheet)
     animation_tools_button.clicked.connect(self.pressControlPanelButton)
         
     world_tools_button.click()
Exemplo n.º 25
0
class EditMap(QWidget):  # класс для создания карты
    def __init__(self):
        self._sp_map = []
        self._elem_map = []
        self._activ_pic = 0
        self._mouse_x = 0
        self._mouse_y = 0
        self._flag_1 = False
        self._flag_2 = True
        self._col = 14
        self._row = 14
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowFlags(Qt.Window | Qt.WindowTitleHint
                            | Qt.CustomizeWindowHint)  #
        self.setMouseTracking(True)  # отслеживаем положение мыши
        self.resize(200,
                    100)  # задаем размер окна с параметрами размеров карты
        self.center()  # отцентровываем окно относительно экрана

        self.setWindowTitle('Редактор карты')

        self.input_col = QLineEdit(str(self._col),
                                   self)  # создаем строку для ввода x
        self.input_col.resize(50, 25)  # задаем размер строки для ввода x
        self.input_col.move(
            30, 0
        )  # задаем положение строки для ввода x в окне с параметрами размеров карты

        self.input_row = QLineEdit(str(self._row),
                                   self)  # создаем строку для ввода y
        self.input_row.resize(50, 25)  # задаем размер строки для ввода y
        self.input_row.move(
            120, 0
        )  # задаем положение строки для ввода y в окне с параметрами размеров карты

        self.button_new_map = QPushButton(
            "СОЗДАТЬ КАРТУ", self)  # создаем кнопку "СОЗДАТЬ КАРТУ"
        self.button_new_map.resize(140,
                                   50)  # задаем размер кнопки "СОЗДАТЬ КАРТУ"
        self.button_new_map.move(
            30, 50
        )  # задаем положение кнопки "СОЗДАТЬ КАРТУ" в окне с параметрами размеров карты
        self.button_new_map.clicked.connect(
            self.new_map)  # ждем событие от кнопки "СОЗДАТЬ КАРТУ"

        self.button_create = QPushButton("СОЗДАТЬ",
                                         self)  # создаем кнопку "СОЗДАТЬ"
        self.button_create.resize(70, 30)  # задаем размер кнопки "СОЗДАТЬ"
        self.button_create.setVisible(False)  # прячем кнопку "СОЗДАТЬ"
        self.button_create.clicked.connect(
            self.create_map)  # ждем событие от кнопки "СОЗДАТЬ"

        self.button_open = QPushButton("ОТКРЫТЬ",
                                       self)  # создаем  кнопку "ОТКРЫТЬ"
        self.button_open.resize(70, 30)  # задаем размер кнопки "ОТКРЫТЬ"
        self.button_open.setVisible(False)  # прячем кнопку "ОТКРЫТЬ"
        self.button_open.clicked.connect(
            self.open_map)  # ждем событие от кнопки "ОТКРЫТЬ"

        self.button_save = QPushButton('СОХРАНИТЬ',
                                       self)  # создаем кнопку "СОХРАНИТЬ"
        self.button_save.resize(70, 30)  # задаем размер кнопки "СОХРАНИТЬ"
        self.button_save.setVisible(False)  # прячем кнопку "СОХРАНИТЬ"
        self.button_save.clicked.connect(
            self.save_map)  # ждем событие от кнопки "СОХРАНИТЬ"

        self.button_back = QPushButton("НАЗАД", self)  # создаем кнопку "НАЗАД"
        self.button_back.resize(70, 30)  # задаем размер кнопки "НАЗАД"
        self.button_back.setVisible(False)  # прячем кнопку "НАЗАД"
        self.button_back.clicked.connect(
            self.close)  # ждем событие от кнопки "НАЗАД"

        self.timer_edit_map = QTimer()
        self.timer_edit_map.timeout.connect(self.updateValues)
        self.timer_edit_map.start(200)

    def new_map(self):  # метод класса Edit_Map, новая карта
        if (not self.input_col.text().isdigit() or not self.input_row.text().isdigit()) or \
                (int(self.input_col.text()) < 14 or int(self.input_row.text()) < 14):
            # проверяем значения x, y. Если не числа, то выводим окно ошибки
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("Error")  # текст окна msg
            msg.setWindowTitle("Error")  # название окна msg
            msg.exec_()
            return

        self._col = int(self.input_col.text())  # запоминаем новое значение x
        self._row = int(self.input_row.text())  # запоминаем новое значение y
        self._sp_map = [[0 for i in range(self._col)] for j in range(self._row)
                        ]  # создаем список 0 по размерам x, y

        self.input_col.setVisible(False)  # прячем строку для ввода x
        self.input_row.setVisible(False)  # прячем строку для ввода y
        self.button_new_map.setVisible(False)  # прячем кнопку "СОЗДАТЬ КАРТУ"

        edit_map.move_button(
        )  # Расширяем окно и меняем положение кнопок "ОТКРЫТЬ", "НАЗАД", "СОЗДАТЬ", "СОХРАНИТЬ"

        self.button_back.setVisible(True)  # показываем кнопку "НАЗАД"
        self.button_save.setVisible(True)  # показываем кнопку "СОХРАНИТЬ"
        self.button_open.setVisible(True)  # показываем кнопку "ОТКРЫТЬ"
        self.button_create.setVisible(True)  # показываем кнопку "СОЗДАТЬ"
        self.center()  # отцентровываем окно относительно экрана

        for i in range(
                PIC
        ):  # записываем в elem_map изображения из которых будет состоять карта
            self._elem_map.append(QPixmap())
            self._elem_map[i].load(resource_path("PIC/" + str(i) + "_0.png"))
        self._flag_1 = True

    def center(self):  # функция отцентровывает окно относительно окна
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def paintEvent(self, event):
        if self._flag_1:
            qp = QPainter()
            qp.begin(self)

            qp.setBrush(QColor(255, 237,
                               0))  # задаем желтый цвет для рамки выбора
            qp.drawRect(self._col * 40 + 15, self._activ_pic * 50, 50,
                        50)  # задаем положение и размер рамки выбора

            for i in range(self._col):
                for j in range(self._row):
                    qp.setBrush(QColor(50, 50, 50))
                    qp.drawRect(i * 40, j * 40, 40, 40)
                    qp.drawPixmap(i * 40, j * 40, self._elem_map[
                        self._sp_map[j][i]])  # рисуем картинками из elem_map

            for i in range(PIC):
                qp.drawPixmap(self._col * 40 + 20, i * 50 + 5,
                              self._elem_map[i])

            if self._mouse_x < self._col * 40 and self._mouse_y < self._row * 40:
                qp.drawPixmap(self._mouse_x - 30, self._mouse_y - 30,
                              self._elem_map[self._activ_pic])
            qp.end()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            if self._mouse_x < self._col * 40 and self._mouse_y < self._row * 40:
                self._sp_map[self._mouse_y // 40][self._mouse_x //
                                                  40] = self._activ_pic
            for i in range(PIC):
                if self._col * 40 + 20 < self._mouse_x < self._col * 40 + 80 and \
                        i * 50 + 5 < self._mouse_y < i * 50 + 65:
                    self._activ_pic = i
                    break

    def mouseMoveEvent(self, event):
        self._mouse_x = event.x()
        self._mouse_y = event.y()

    def create_map(self):
        self.button_create.setVisible(False)
        self.button_open.setVisible(False)
        self.button_save.setVisible(False)
        self.button_back.setVisible(False)
        self._flag_1 = False
        self.input_col.setVisible(True)
        self.input_row.setVisible(True)
        self.button_new_map.setVisible(True)
        self.resize(200, 100)
        self.center()

    def save_map(self):
        stroka = ''
        for j in range(self._row):
            for i in range(self._col):
                stroka += str(self._sp_map[j][i])
            stroka += '\n'
        file_save_map = QFileDialog.getSaveFileName(self, filter='*.map')[0]
        if file_save_map != '':
            f = open(file_save_map, 'w', encoding="utf8")
            with f:
                f.write(stroka[:-1])
                self._flag_2 = False
            f.close()

    def open_map(self):
        file_save_map = QFileDialog.getOpenFileName(self, filter='*.map')[0]
        f = open(file_save_map, encoding="utf8")
        with f:
            old_map = f.readlines()
        f.close()
        self._row = len(old_map)
        self._col = len(old_map[0]) - 1
        self._sp_map = []
        for j in range(self._row):
            self._sp_map.append([])
            for i in range(self._col):
                self._sp_map[j].append(int(old_map[j][i]))
        edit_map.move_button()
        self.center()

    def close(self):
        if self._flag_2:
            result = QMessageBox.question(self, "ПРЕДУПРЕЖДЕНИЕ!",
                                          "Сохранить карту?",
                                          QMessageBox.Yes | QMessageBox.No,
                                          QMessageBox.No)
            if result == QMessageBox.Yes:
                edit_map.save_map()
        self.setVisible(False)
        game.setVisible(True)

    def updateValues(self):
        self.update()

    def move_button(self):
        self.resize(self._col * 40 + 100, self._row * 40)
        # расширяем окно по параметрам x, y, добавляем 100 по х для elem_map
        self.button_back.move(self._col * 40 + 15, self._row * 40 -
                              30)  # задаем положение кнопки "НАЗАД"
        self.button_save.move(self._col * 40 + 15, self._row * 40 -
                              60)  # задаем положение кнопки "СОХРАНИТЬ"
        self.button_open.move(self._col * 40 + 15, self._row * 40 -
                              90)  # задаем положение кнопки "ОТКРЫТЬ"
        self.button_create.move(self._col * 40 + 15, self._row * 40 -
                                120)  # задаем положение кнопки "СОЗДАТЬ"
class StickmanToolsPanel(QFrame):
    
    WIDTH = 1100
    HEIGHT = 45
    
    FRAME_SIZE_X = 180
    FRAME_WIDTH = 1
    FRAME_MARGIN = 2
    
    ICON_SIZE = 35
    ICON_BUTTON_WIDTH = 60
    INPUT_TEXT_WIDTH = 300
    INPUT_START_X = 213
    SAY_BLOCK_X = 520
    PHOTO_BUTTON_WIDTH = 240
    PHOTO_BUTTON_X = 858
    
    def __init__(self, parent, tools):
        super().__init__(parent)
        self.tools = tools
        self.initUI()
        
    def initUI(self):
        self.resize(StickmanToolsPanel.WIDTH, StickmanToolsPanel.HEIGHT + StickmanToolsPanel.FRAME_MARGIN*2)
        self.setFrameStyle(QFrame.StyledPanel)
        self.setFrameRect(QRect(0, 0, StickmanToolsPanel.FRAME_SIZE_X + StickmanToolsPanel.FRAME_MARGIN*2, StickmanToolsPanel.HEIGHT + StickmanToolsPanel.FRAME_MARGIN*2))
        self.setLineWidth(StickmanToolsPanel.FRAME_WIDTH)
        
        component_stylesheet = """
                                .QPushButton {
                                    font-weight: bold;
                                    font-size: 13px;
                                    background-color:#E0E0E0;
                                }
                                .QPushButton:pressed {
                                    background-color:#CCCCCC;
                                }
                                .QLineEdit {
                                    font-weight: bold;
                                    font-size: 24px;
                                }  
                            """
                        
        self.smile_button = QPushButton('', self)
        self.smile_button.setIcon(assets.smile)
        self.smile_button.setIconSize(QSize(StickmanToolsPanel.ICON_SIZE, StickmanToolsPanel.ICON_SIZE))
        self.smile_button.resize(StickmanToolsPanel.ICON_BUTTON_WIDTH, StickmanToolsPanel.HEIGHT)
        self.smile_button.move(StickmanToolsPanel.FRAME_MARGIN, StickmanToolsPanel.FRAME_MARGIN)        
        self.smile_button.setStyleSheet(component_stylesheet)
        self.smile_button.clicked.connect(self.changeExpression)
        self.smile_button.show()        

        self.sad_button = QPushButton('', self)
        self.sad_button.setIcon(assets.sad)
        self.sad_button.setIconSize(QSize(StickmanToolsPanel.ICON_SIZE, StickmanToolsPanel.ICON_SIZE))
        self.sad_button.resize(StickmanToolsPanel.ICON_BUTTON_WIDTH, StickmanToolsPanel.HEIGHT)
        self.sad_button.move(StickmanToolsPanel.FRAME_MARGIN + StickmanToolsPanel.ICON_BUTTON_WIDTH, StickmanToolsPanel.FRAME_MARGIN)        
        self.sad_button.setStyleSheet(component_stylesheet)
        self.sad_button.clicked.connect(self.changeExpression)
        self.sad_button.show() 
        
        self.confused_button = QPushButton('', self)
        self.confused_button.setIcon(assets.confused)
        self.confused_button.setIconSize(QSize(StickmanToolsPanel.ICON_SIZE, StickmanToolsPanel.ICON_SIZE))
        self.confused_button.resize(StickmanToolsPanel.ICON_BUTTON_WIDTH, StickmanToolsPanel.HEIGHT)
        self.confused_button.move(StickmanToolsPanel.FRAME_MARGIN + StickmanToolsPanel.ICON_BUTTON_WIDTH*2, StickmanToolsPanel.FRAME_MARGIN)        
        self.confused_button.setStyleSheet(component_stylesheet)
        self.confused_button.clicked.connect(self.changeExpression)
        self.confused_button.show() 
        
        self.say_text = QLineEdit(self)
        self.say_text.setStyleSheet(component_stylesheet)
        self.say_text.resize(StickmanToolsPanel.INPUT_TEXT_WIDTH, StickmanToolsPanel.HEIGHT)
        self.say_text.move(StickmanToolsPanel.FRAME_MARGIN + StickmanToolsPanel.INPUT_START_X, StickmanToolsPanel.FRAME_MARGIN)
        
        self.say_left = QPushButton('', self)
        self.say_left.setIcon(assets.say_left)
        self.say_left.setIconSize(QSize(StickmanToolsPanel.ICON_SIZE, StickmanToolsPanel.ICON_SIZE))
        self.say_left.resize(StickmanToolsPanel.ICON_BUTTON_WIDTH, StickmanToolsPanel.HEIGHT)
        self.say_left.move(StickmanToolsPanel.SAY_BLOCK_X, StickmanToolsPanel.FRAME_MARGIN)        
        self.say_left.setStyleSheet(component_stylesheet)
        self.say_left.clicked.connect(self.sayLeft)
        
        self.say_right = QPushButton('', self)
        self.say_right.setIcon(assets.say_right)
        self.say_right.setIconSize(QSize(StickmanToolsPanel.ICON_SIZE, StickmanToolsPanel.ICON_SIZE))
        self.say_right.resize(StickmanToolsPanel.ICON_BUTTON_WIDTH, StickmanToolsPanel.HEIGHT)
        self.say_right.move(StickmanToolsPanel.SAY_BLOCK_X + StickmanToolsPanel.ICON_BUTTON_WIDTH, StickmanToolsPanel.FRAME_MARGIN)   
        self.say_right.setStyleSheet(component_stylesheet)
        self.say_right.clicked.connect(self.sayRight)
        
        self.say_exit = QPushButton('', self)
        self.say_exit.setIcon(assets.exit)
        self.say_exit.setIconSize(QSize(StickmanToolsPanel.ICON_SIZE, StickmanToolsPanel.ICON_SIZE))
        self.say_exit.resize(StickmanToolsPanel.ICON_BUTTON_WIDTH, StickmanToolsPanel.HEIGHT)
        self.say_exit.move(StickmanToolsPanel.SAY_BLOCK_X + StickmanToolsPanel.ICON_BUTTON_WIDTH*2, StickmanToolsPanel.FRAME_MARGIN)   
        self.say_exit.setStyleSheet(component_stylesheet)
        self.say_exit.clicked.connect(self.sayClear)
        
        self.photo = QPushButton('', self)
        self.photo.setIcon(assets.camera)
        self.photo.setIconSize(QSize(StickmanToolsPanel.ICON_SIZE, StickmanToolsPanel.ICON_SIZE))
        self.photo.resize(StickmanToolsPanel.PHOTO_BUTTON_WIDTH, StickmanToolsPanel.HEIGHT)
        self.photo.move(StickmanToolsPanel.PHOTO_BUTTON_X, StickmanToolsPanel.FRAME_MARGIN)
        self.photo.setStyleSheet(component_stylesheet)
        self.photo.clicked.connect(self.makePhoto)
        
    def sayLeft(self):
        search = getWorld().getActive()
        if search != None:
            search.sayLeft(self.say_text.text())
        self.say_text.setText("")
    def sayRight(self):
        search = getWorld().getActive()
        if search != None:
            search.sayRight(self.say_text.text())
        self.say_text.setText("")
    def sayClear(self):
        search = getWorld().getActive()
        if search != None:
            search.sayRemove()
        self.say_text.setText("")
    
    def changeExpression(self):
        search = getWorld().getActive()
        if search != None:
            if self.sender() == self.smile_button:
                search.setHappy()
            elif self.sender() == self.sad_button:
                search.setSad()
            else:
                search.setConfused()
    
    def makePhoto(self):
        self.tools.framemenu.addNewFrame(getWorld().getFrame())
Exemplo n.º 27
0
class MainIndex(QWidget):
    auto_pressed_sg = pyqtSignal(dict)
    home_pressed_sg = pyqtSignal()
    search_pressed_sg = pyqtSignal()

    def __init__(self, parent=None):
        super(MainIndex, self).__init__(parent)
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.h = self.screenRect.height()
        self.w = self.screenRect.width()
        self.xr = self.w / 930
        self.yr = self.h / 640
        self.zr = min(self.xr, self.yr)
        self.token = ''
        self.top_wi = QWidget(self)
        self.logo_la = QLabel(self.top_wi)
        self.manual_but = QPushButton(self)
        # self.manual_tex = QLabel(self)
        self.auto_but = QPushButton(self)
        # self.auto_tex = QLabel(self)
        self.home_but = QPushButton(self)
        # self.home_tex = QLabel(self)
        self.loading = QLabel(self)
        self.gif = QMovie('./resource/image/load.gif')
        self.set_ui()
        with open('mainindex.qss', 'r') as f:
            self.setStyleSheet(f.read())

    def set_ui(self):
        self.setWindowTitle('Hall')
        self.setObjectName('hall')
        self.resize(self.w, self.h)
        effect1 = QGraphicsDropShadowEffect()
        effect1.setOffset(10, 10)
        effect1.setColor(QColor(0, 0, 0, 80))
        effect1.setBlurRadius(20)
        effect2 = QGraphicsDropShadowEffect()
        effect2.setOffset(10, 10)
        effect2.setColor(QColor(0, 0, 0, 80))
        effect2.setBlurRadius(20)
        effect3 = QGraphicsDropShadowEffect()
        effect3.setOffset(10, 10)
        effect3.setColor(QColor(0, 0, 0, 80))
        effect3.setBlurRadius(20)
        self.top_wi.setObjectName('top')
        self.top_wi.resize(self.xr * 930, self.yr * 95)
        self.logo_la.setObjectName('logo')
        self.logo_la.resize(self.xr * 65, self.zr * 65)
        self.logo_la.move(self.xr * 29, self.yr * 16)
        self.manual_but.setObjectName('box')
        self.manual_but.resize(self.xr * 180, self.yr * 320)
        self.manual_but.move(self.xr * 112, self.yr * 194)
        self.manual_but.setText(change_vertical('战局搜索'))
        self.manual_but.setStyleSheet(
            'border-radius:{}px;font-size:{}px;'.format(
                self.zr * 20, int(self.zr * 30)))
        self.manual_but.setGraphicsEffect(effect1)
        self.manual_but.clicked.connect(self.search_press)
        # self.manual_tex.setObjectName('manual_tex')
        # self.manual_tex.resize(self.xr * 34, self.yr * 413)
        # self.manual_tex.move(self.xr * 68, self.yr * 152)
        # self.manual_tex.setText(change_vertical('是当一辈子的懦夫,还是三十秒的勇士?'))
        # self.manual_tex.setStyleSheet('font-size:{}px;'.format(int(self.zr * 17)))
        self.auto_but.setObjectName('box')
        self.auto_but.resize(self.xr * 180, self.yr * 320)
        self.auto_but.move(self.xr * 381, self.yr * 194)
        self.auto_but.setText(change_vertical('自动场'))
        self.auto_but.setStyleSheet(
            'border-radius:{}px;font-size:{}px;'.format(
                self.zr * 20, int(self.zr * 30)))
        self.auto_but.setGraphicsEffect(effect2)
        self.auto_but.clicked.connect(self.auto_press)
        # self.auto_tex.setObjectName('auto_tex')
        # self.auto_tex.resize(self.xr * 34, self.yr * 413)
        # self.auto_tex.move(self.xr * 340, self.yr * 152)
        # self.auto_tex.setText(change_vertical('机器就要由机器来终结'))
        # self.auto_tex.setStyleSheet('font-size:{}px;'.format(int(self.zr * 17)))
        self.home_but.setObjectName('box')
        self.home_but.resize(self.xr * 180, self.yr * 320)
        self.home_but.move(self.xr * 660, self.yr * 194)
        self.home_but.setText(change_vertical('沙之家'))
        self.home_but.setStyleSheet(
            'border-radius:{}px;font-size:{}px;'.format(
                self.zr * 20, int(self.zr * 30)))
        self.home_but.setGraphicsEffect(effect3)
        self.home_but.clicked.connect(self.home_press)
        # self.home_tex.setObjectName('home_tex')
        # self.home_tex.resize(self.xr * 34, self.yr * 413)
        # self.home_tex.move(self.xr * 610, self.yr * 152)
        # self.home_tex.setText(change_vertical('常回家看看!'))
        # self.home_tex.setStyleSheet('font-size:{}px;'.format(int(self.zr * 17)))
        self.loading.setObjectName('load')
        self.loading.resize(self.xr * 150, self.yr * 150)
        self.loading.move(self.xr * 760, self.yr * 500)
        self.loading.setScaledContents(True)
        self.loading.setMovie(self.gif)
        self.gif.start()

    def auto_press(self):
        res = play(self.token)
        if res["status"] == 0:
            self.auto_pressed_sg.emit(res)

    def home_press(self):
        self.home_pressed_sg.emit()

    def search_press(self):
        self.search_pressed_sg.emit()

    def get_token(self, t):
        self.token = t
Exemplo n.º 28
0
class WorldToolsPanel(QFrame):
    
    FRAME_WIDTH = 1
    FRAME_MARGIN = 2
    TOOLS_WIDTH = 600
    TOOLS_HEIGHT = 30
    
    INPUT_WIDTH = 585    
    BUTTON_WIDTH = 150    
    
    STICKMAN_X = 300
    STICKMAN_Y = 100
    STICKMAN_NAME_MAX_LENGTH = 15   
    
    def __init__(self, parent):
        super().__init__(parent)
        self.initUI()
        
    def initUI(self):        
        self.setFrameStyle(QFrame.StyledPanel)
        self.setLineWidth(WorldToolsPanel.FRAME_WIDTH)
        
        self.resize(WorldToolsPanel.TOOLS_WIDTH + WorldToolsPanel.FRAME_MARGIN*2, WorldToolsPanel.TOOLS_HEIGHT + WorldToolsPanel.FRAME_MARGIN*2)
        self.setFrameRect(QRect(0, 0, WorldToolsPanel.TOOLS_WIDTH + WorldToolsPanel.FRAME_MARGIN*2, WorldToolsPanel.TOOLS_HEIGHT + WorldToolsPanel.FRAME_MARGIN*2))        
        
        button_stylesheet = """
                                .QPushButton {
                                    font-weight: bold;
                                    font-size: 13px;
                                    background-color:#E0E0E0;
                                }
                                .QPushButton:pressed {
                                    background-color:#CCCCCC;
                                }
                            """
                        
        self.create_stickman = QPushButton('Create Stickman', self)
        self.create_stickman.resize(WorldToolsPanel.BUTTON_WIDTH, WorldToolsPanel.TOOLS_HEIGHT)
        self.create_stickman.move(WorldToolsPanel.FRAME_WIDTH*2, WorldToolsPanel.FRAME_MARGIN)        
        self.create_stickman.setStyleSheet(button_stylesheet)
        self.create_stickman.clicked.connect(self.showCreateDialog)
        
        self.create_stickman_input = InputLine(self)
        self.create_stickman_input.setLabelText("Enter New StickName: ")
        self.create_stickman_input.addOkListener(self.readCreateName)
        self.create_stickman_input.addCancelListener(self.hideCreateDialog)
        self.create_stickman_input.move(WorldToolsPanel.FRAME_MARGIN, WorldToolsPanel.FRAME_MARGIN)
        self.create_stickman_input.hide()
        
        self.delete_stickman = QPushButton('Delete Stickman', self)
        self.delete_stickman.resize(WorldToolsPanel.BUTTON_WIDTH, WorldToolsPanel.TOOLS_HEIGHT)
        self.delete_stickman.move(WorldToolsPanel.BUTTON_WIDTH + WorldToolsPanel.FRAME_MARGIN, WorldToolsPanel.FRAME_MARGIN)        
        self.delete_stickman.setStyleSheet(button_stylesheet)
        self.delete_stickman.clicked.connect(self.showDeleteDialog)
        
        self.delete_stickman_input = InputLine(self)
        self.delete_stickman_input.setLabelText("Enter Name to Delete: ")
        self.delete_stickman_input.addOkListener(self.readDeleteName)
        self.delete_stickman_input.addCancelListener(self.hideDeleteDialog)
        self.delete_stickman_input.move(WorldToolsPanel.FRAME_MARGIN, WorldToolsPanel.FRAME_MARGIN)
        self.delete_stickman_input.hide()
        
        self.change_background = QPushButton('Set Background', self)
        self.change_background.resize(WorldToolsPanel.BUTTON_WIDTH, WorldToolsPanel.TOOLS_HEIGHT)
        self.change_background.move(WorldToolsPanel.BUTTON_WIDTH*2 + WorldToolsPanel.FRAME_MARGIN, WorldToolsPanel.FRAME_MARGIN)        
        self.change_background.setStyleSheet(button_stylesheet)
        self.change_background.clicked.connect(self.findBackground)
        
        self.remove_background = QPushButton('Clear Background', self)
        self.remove_background.resize(WorldToolsPanel.BUTTON_WIDTH, WorldToolsPanel.TOOLS_HEIGHT)
        self.remove_background.move(WorldToolsPanel.BUTTON_WIDTH*3 + WorldToolsPanel.FRAME_MARGIN, WorldToolsPanel.FRAME_MARGIN)        
        self.remove_background.setStyleSheet(button_stylesheet)       
        self.remove_background.clicked.connect(self.clearBackground)
        
    """ Methods which show and hide input lines and buttons. ALso methods for resizing the panel and its frame """
    def showCreateDialog(self):
        self.resizeForInput()
        self.hideButtons()  
        self.create_stickman_input.setText("")
        self.create_stickman_input.setErrorText("")
        self.create_stickman_input.show() 
    def hideCreateDialog(self):        
        self.resizeForButtons()
        self.create_stickman_input.hide()  
        self.showButtons()
        
    def showDeleteDialog(self):
        self.resizeForInput()
        self.hideButtons()
        self.delete_stickman_input.setText("")
        self.delete_stickman_input.setErrorText("")
        self.delete_stickman_input.show() 
    def hideDeleteDialog(self):
        self.resizeForButtons()
        self.delete_stickman_input.hide()  
        self.showButtons()
        
    def hideButtons(self):
        self.create_stickman.hide()
        self.delete_stickman.hide()
        self.change_background.hide()
        self.remove_background.hide()       
    def showButtons(self):
        self.create_stickman.show()
        self.delete_stickman.show()
        self.change_background.show()
        self.remove_background.show()
    
    def resizeForButtons(self):
        self.resize(WorldToolsPanel.TOOLS_WIDTH + WorldToolsPanel.FRAME_MARGIN*2, WorldToolsPanel.TOOLS_HEIGHT + WorldToolsPanel.FRAME_MARGIN*2)
        self.setFrameRect(QRect(0, 0, WorldToolsPanel.TOOLS_WIDTH + WorldToolsPanel.FRAME_MARGIN*2, WorldToolsPanel.TOOLS_HEIGHT + WorldToolsPanel.FRAME_MARGIN*2))  
    def resizeForInput(self):    
        self.resize(WorldToolsPanel.INPUT_WIDTH + WorldToolsPanel.FRAME_MARGIN*2 + InputLine.ERROR_WIDTH, WorldToolsPanel.TOOLS_HEIGHT + WorldToolsPanel.FRAME_MARGIN*2)
        self.setFrameRect(QRect(0, 0, WorldToolsPanel.INPUT_WIDTH + WorldToolsPanel.FRAME_MARGIN*2, WorldToolsPanel.TOOLS_HEIGHT + WorldToolsPanel.FRAME_MARGIN*2))   
    
    """ listener for the file dialog method to open the file for the background"""
    def findBackground(self):
        file = QFileDialog.getOpenFileName(self, "Open Image", ".", "Image Files (*.png *.jpg)")
        if file[0] != "":
            getWorld().setBackground(file[0])
    def clearBackground(self):
        getWorld().clearBackground("#FFFFFF")
           
    """ Listeners to take actions when ok button was pressed and input text has been read """
    def readCreateName(self):
        if self.create_stickman_input.getText() == "":
            self.create_stickman_input.setErrorText("StickName cannot be empty!")
        elif getWorld().exists(self.create_stickman_input.getText()):
            self.create_stickman_input.setErrorText("This StickName is already taken!")
            self.create_stickman_input.setText("")
        elif len(self.create_stickman_input.getText()) >  WorldToolsPanel.STICKMAN_NAME_MAX_LENGTH:
            self.create_stickman_input.setErrorText("StickName is too long!")
            self.create_stickman_input.setText("")
        else:
            getWorld().createStickman(self.create_stickman_input.getText(), WorldToolsPanel.STICKMAN_X, WorldToolsPanel.STICKMAN_Y)
            self.hideCreateDialog()
                   
    def readDeleteName(self):
        if self.delete_stickman_input.getText() == "":
            self.delete_stickman_input.setErrorText("StickName cannot be empty!")
        elif not getWorld().exists(self.delete_stickman_input.getText()):
            self.delete_stickman_input.setErrorText("This StickName does not exist!")
            self.delete_stickman_input.setText("")
        else:
            getWorld().removeStickman(self.delete_stickman_input.getText())
            self.hideDeleteDialog()
Exemplo n.º 29
0
class StickmanList(QWidget):
    
    MARGIN_TOP = 20
    
    BUTTON_WIDTH = 240
    BUTTON_HEIGHT = 40
    BUTTON_GAP = 5
    MAX_LENGTH = 10
    
    ICON_SIZE = 25
    EVENT_SHIFT_X = 845
    
    def __init__(self, parent):
        super().__init__(parent)
        self.resize(StickmanList.BUTTON_WIDTH, StickmanList.BUTTON_HEIGHT*(StickmanList.MAX_LENGTH + 2) + StickmanList.MARGIN_TOP)
        self.initUI()        
                
    def initUI(self):
        self.buttons = list()
        
        self.button_style_passive = """
                          .QPushButton {
                              font-weight: bold;
                              font-size: 20px;
                              background-color:#D3D3D3;
                              border: 1px solid black;
                          }
                      """
        self.button_style_active = """
                          .QPushButton {
                              font-weight: bold;
                              font-size: 20px;
                              background-color:#B4B4B4;
                              border: 2px solid black;
                          }
                      """
                       
        getWorld().addListener(self.onStickmanListener)
        
        """ These are the buttons to control list of names scrolling. start_index is the index which points to the 
            first entry in the button list which is currently shown at the top of the visual list. """
        scroll_button_style = """
                                 .QPushButton {
                                      font-weight: bold;
                                      font-size: 20px;
                                      background-color:#D3D3D3;
                                  }
                                  .QPushButton:pressed {
                                      background-color:#B4B4B4;
                                  }       
                               """
        
        self.scroll_up_button = QPushButton("", self)
        self.scroll_up_button.setIcon(assets.up)
        self.scroll_up_button.setIconSize(QSize(StickmanList.ICON_SIZE*2, StickmanList.ICON_SIZE))
        self.scroll_up_button.resize(StickmanList.BUTTON_WIDTH/2, StickmanList.BUTTON_HEIGHT)        
        self.scroll_up_button.move(0, StickmanList.BUTTON_HEIGHT*(StickmanList.MAX_LENGTH + 1) + StickmanList.MARGIN_TOP)
        self.scroll_up_button.setStyleSheet(scroll_button_style)
        self.scroll_up_button.clicked.connect(self.scrollListUp)
        self.scroll_up_button.hide()
            
        self.scroll_down_button = QPushButton("", self)
        self.scroll_down_button.setIcon(assets.down)
        self.scroll_down_button.setIconSize(QSize(StickmanList.ICON_SIZE*2, StickmanList.ICON_SIZE))
        self.scroll_down_button.resize(StickmanList.BUTTON_WIDTH/2, StickmanList.BUTTON_HEIGHT)
        self.scroll_down_button.move(StickmanList.BUTTON_WIDTH/2, StickmanList.BUTTON_HEIGHT*(StickmanList.MAX_LENGTH + 1) + StickmanList.MARGIN_TOP)
        self.scroll_down_button.setStyleSheet(scroll_button_style)
        self.scroll_down_button.clicked.connect(self.scrollListDown)
        self.scroll_down_button.hide()
        
        self.start_index = 0    #required to track the first element in the list which is shown
        
    """ fixes button positions on the stickmen list after button addition or removal. 
        activates/deactivates buttons depending on which stickman is active.
        In case there are morre than 10 buttons, shows scrolling buttons. Controls which buttons are hidden and which are shown. """            
    def rearrangeButtons(self):    
        i = 0
        for button in self.buttons:
            if i < self.start_index:
                button.hide()
            elif i > (self.start_index + StickmanList.MAX_LENGTH - 1):
                button.hide()
            else:
                button.show()
                button.move(0, (i-self.start_index)*(StickmanList.BUTTON_HEIGHT + StickmanList.BUTTON_GAP))
                if getWorld().isActive(button.text()):
                    button.setStyleSheet(self.button_style_active)
                else:
                    button.setStyleSheet(self.button_style_passive)
            i = i+1 
            
        if len(self.buttons) > StickmanList.MAX_LENGTH:
            self.scroll_up_button.show()
            self.scroll_down_button.show()
        else:
            self.scroll_up_button.hide()
            self.scroll_down_button.hide()
    
    def scrollListUp(self):
        if self.start_index > 0:
            self.start_index = self.start_index - 1
            self.rearrangeButtons()
                       
    def scrollListDown(self):
        if self.start_index < len(self.buttons) - StickmanList.MAX_LENGTH:
            self.start_index = self.start_index + 1
            self.rearrangeButtons()
                
    """ listener method which create on-screen buttons with stickman names or remove them. It redraws buttons if active state changes. Called from the World class """
    def onStickmanListener(self, name, operation):
        if operation == World.ADD_EVENT:
            button = QPushButton(name, self)
            button.resize(StickmanList.BUTTON_WIDTH, StickmanList.BUTTON_HEIGHT)
            button.clicked.connect(self.onMousePressed)
            button.show()
            self.buttons.insert(0, button)    
            self.start_index = 0    
            self.rearrangeButtons()
        elif operation == World.REMOVE_EVENT:
            for button in self.buttons:
                if button.text() == name:
                    self.buttons.remove(button)
                    button.setParent(None)
                    if self.start_index > 0:
                        self.start_index = self.start_index - 1
                    self.rearrangeButtons()
        elif operation == World.ACTIVE_EVENT:
            self.rearrangeButtons()
    
    """ listener method used to switch active states of stickmen """
    def onMousePressed(self):
        getWorld().setActive(self.sender().text())
    
    """ these listeners are required to pass mouse events to the canvas in case there are any, making this list transparent as a result """
    def mousePressEvent(self, event):
        getWorld().mousePressed(event.x() + StickmanList.EVENT_SHIFT_X, event.y() + StickmanList.MARGIN_TOP)   
        
    def mouseReleaseEvent(self, event):
        getWorld().mouseReleased(event.x() + StickmanList.EVENT_SHIFT_X, event.y() + StickmanList.MARGIN_TOP) 
    
    def mouseMoveEvent(self, event):
        getWorld().mouseMoved(event.x() + StickmanList.EVENT_SHIFT_X, event.y() + StickmanList.MARGIN_TOP) 
Exemplo n.º 30
0
class FrameList(QWidget):
    
    BUTTON_WIDTH = 240
    BUTTON_HEIGHT = 40
    
    MARGIN_TOP = 20
    BUTTON_GAP = 5
    MAX_LENGTH = 10
    
    ICON_SIZE = 25
    EVENT_SHIFT_X = 845
    
    def __init__(self, parent):
        super().__init__(parent)
        self.resize(FrameList.BUTTON_WIDTH, FrameList.BUTTON_HEIGHT*(FrameList.MAX_LENGTH+2) + FrameList.MARGIN_TOP)
        self.initUI()
                
    def initUI(self):
        self.buttons = FrameMap()
        
        self.button_style_passive = """
                          .QPushButton {
                              font-weight: bold;
                              font-size: 20px;
                              background-color:#D3D3D3;
                              border: 1px solid black;
                          }
                      """
        self.button_style_active = """
                          .QPushButton {
                              font-weight: bold;
                              font-size: 20px;
                              background-color:#B4B4B4;
                              border: 2px solid black;
                          }
                      """
        
        """ These are the buttons to control list of names scrolling. start_index is the index which points to the 
            first entry in the button list which is currently shown at the top of the visual list. """
        scroll_button_style = """
                                 .QPushButton {
                                      font-weight: bold;
                                      font-size: 20px;
                                      background-color:#D3D3D3;
                                  }
                                  .QPushButton:pressed {
                                      background-color:#B4B4B4;
                                  }       
                               """
        
        self.scroll_up_button = QPushButton("", self)
        self.scroll_up_button.setIcon(assets.up)
        self.scroll_up_button.setIconSize(QSize(FrameList.ICON_SIZE*2, FrameList.ICON_SIZE))
        self.scroll_up_button.resize(FrameList.BUTTON_WIDTH/2, FrameList.BUTTON_HEIGHT)        
        self.scroll_up_button.move(0, FrameList.BUTTON_HEIGHT*(FrameList.MAX_LENGTH+1) + FrameList.MARGIN_TOP)
        self.scroll_up_button.setStyleSheet(scroll_button_style)
        self.scroll_up_button.clicked.connect(self.scrollListUp)
        self.scroll_up_button.hide()
            
        self.scroll_down_button = QPushButton("", self)
        self.scroll_down_button.setIcon(assets.down)
        self.scroll_down_button.setIconSize(QSize(FrameList.ICON_SIZE*2, FrameList.ICON_SIZE))
        self.scroll_down_button.resize(FrameList.BUTTON_WIDTH/2, FrameList.BUTTON_HEIGHT)
        self.scroll_down_button.move(FrameList.BUTTON_WIDTH/2, FrameList.BUTTON_HEIGHT*(FrameList.MAX_LENGTH+1) + FrameList.MARGIN_TOP)
        self.scroll_down_button.setStyleSheet(scroll_button_style)
        self.scroll_down_button.clicked.connect(self.scrollListDown)
        self.scroll_down_button.hide()
        
        self.start_index = 0
    
    """ Methods for changing the frames on the FrameList """
    def addNewFrame(self, frame):
        button = QPushButton("", self)
        button.resize(FrameList.BUTTON_WIDTH, FrameList.BUTTON_HEIGHT)
        button.clicked.connect(self.onMousePressed)
        button.show()
        self.buttons[button] = frame
        if len(self.buttons) > FrameList.MAX_LENGTH:
            self.start_index = len(self.buttons) - FrameList.MAX_LENGTH
        self.rearrangeButtons()
    
    def deleteFrame(self, caller):
        if not self.buttons.active == None:
            response = QMessageBox.question(caller, 'Frame Remove Message', "Are you sure you want to delete this frame?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            if response == QMessageBox.Yes:
                self.buttons.active.setParent(None)
                del self.buttons[self.buttons.active]
                if self.start_index > 0:
                    self.start_index = self.start_index-1
                self.parent().canvas.hideMessage()
        self.rearrangeButtons()
    
    def removeAllFrames(self):
        self.buttons.active = None
        for button in self.buttons.keys().copy():
            button.setParent(None)
            del self.buttons[button]
        self.start_index = 0
        self.rearrangeButtons()
    
    def copyFrame(self):
        if not self.buttons.active == None:            
            button = QPushButton("", self)
            button.resize(FrameList.BUTTON_WIDTH, FrameList.BUTTON_HEIGHT)
            button.clicked.connect(self.onMousePressed)
            button.show()
            
            index = self.buttons.index(self.buttons.active)  
            copy_frame = getWorld().getFrame()
            copy_frame.time = self.buttons[self.buttons.active].time
            self.buttons.insertAt(index+1, button, copy_frame)
            if len(self.buttons) > FrameList.MAX_LENGTH:
                self.start_index = self.start_index + 1
            self.rearrangeButtons()
    
    def changeFrameTime(self, time):
        if not self.buttons.active == None:
            self.buttons[self.buttons.active].time = time
            self.rearrangeButtons()
    
    """ Convenience methods for frame retrieval used by the animation player and some buttons """            
    def getActiveFrame(self):
        if not self.buttons.active == None:
            return (self.buttons.active, self.buttons[self.buttons.active])
        else:
            return None    
    def getFirstFrame(self):
        first_button = self.buttons.first()
        if not first_button == None:
            return self.buttons[first_button]
        else:
            return None    
    def getNextFrame(self, frame):
        return self.buttons.nextValue(frame)
        
    def getAllFrames(self):
        return self.buttons.frames        
    
    """ fixes button positions on the stickmen list after button addition or removal. 
        activates/deactivates buttons depending on which stickman is active.
        In case there are more than 10 buttons, shows scrolling buttons. Controls which buttons are hidden and which are shown. """            
    def rearrangeButtons(self):    
        i = 0
        for button in self.buttons.keys():
            if i == 0:
                button.setText("Frame " + str(i+1) + " : " + "0.0s")
            else:
                button.setText("Frame " + str(i+1) + " : " + str("%0.1f" % (self.buttons[button].time)) + "s") #makes up for removed frames, restoring the naming order
               
            if i < self.start_index:
                button.hide()
            elif i > (self.start_index + FrameList.MAX_LENGTH - 1):
                button.hide()
            else:
                button.show()
                button.move(0, (i-self.start_index)*(FrameList.BUTTON_HEIGHT + FrameList.BUTTON_GAP))
                if button == self.buttons.active:
                    button.setStyleSheet(self.button_style_active)
                else:
                    button.setStyleSheet(self.button_style_passive)
            i = i+1 
        #part which whows or hides up-down scroll buttons    
        if len(self.buttons) > FrameList.MAX_LENGTH:
            self.scroll_up_button.show()
            self.scroll_down_button.show()
        else:
            self.scroll_up_button.hide()
            self.scroll_down_button.hide()
            
        self.parent().tools.animation_tools.showButtonBlock()
                
        
    def scrollListUp(self):
        if self.start_index > 0:
            self.start_index = self.start_index - 1
            self.rearrangeButtons()
                       
    def scrollListDown(self):
        if self.start_index < len(self.buttons)-FrameList.MAX_LENGTH:
            self.start_index = self.start_index + 1
            self.rearrangeButtons()
    
    """ listener method used to switch between currently present frames """
    def onMousePressed(self):
        #sets the world to a copy of the current contents, preserving frame from future changes
        if self.sender() == self.buttons.active:
            self.buttons.active = None
            getWorld().copyWorld()
            self.parent().canvas.hideMessage()
        #sets the world to the current frame contents          
        else:
            open_frame = self.buttons[self.sender()]
            getWorld().setWorldFrom(open_frame)
            self.buttons.active = self.sender()  
            self.parent().canvas.showMessage()       
        self.rearrangeButtons()
    
    """ these listeners are required to pass mouse events to the canvas in case there are any, making this list transparent as a result """
    def mousePressEvent(self, event):
        getWorld().mousePressed(event.x() + FrameList.EVENT_SHIFT_X, event.y() + FrameList.MARGIN_TOP)   
        
    def mouseReleaseEvent(self, event):
        getWorld().mouseReleased(event.x() + FrameList.EVENT_SHIFT_X, event.y() + FrameList.MARGIN_TOP) 
    
    def mouseMoveEvent(self, event):
        getWorld().mouseMoved(event.x() + FrameList.EVENT_SHIFT_X, event.y() + FrameList.MARGIN_TOP)   
class AnimationToolsPanel(QFrame):
    
    WIDTH = 1100
    HEIGHT = 45
    
    FRAME_WIDTH = 1
    FRAME_MARGIN = 2
    
    ICON_SIZE = 35
    ICON_BUTTON_WIDTH = 60
    
    IO_BUTTON_WIDTH = 200
    IO_BLOCK_START_X = 292
    
    TIME_INPUT_X = 698
    BUTTON_BLOCK_X = 918
    
    def __init__(self, parent, tools):
        super().__init__(parent)
        self.tools = tools
        self.initUI()
        
    def initUI(self):
        self.resize(AnimationToolsPanel.WIDTH, AnimationToolsPanel.HEIGHT + AnimationToolsPanel.FRAME_MARGIN*2)
        self.setFrameStyle(QFrame.StyledPanel)
        self.setLineWidth(AnimationToolsPanel.FRAME_WIDTH)
        self.setFrameRect(QRect(290, 0, 404, 49))
               
        button_stylesheet = """
                                .QPushButton {
                                    font-weight: bold;
                                    font-size: 13px;
                                    background-color:#E0E0E0;
                                }
                                .QPushButton:pressed {
                                    background-color:#CCCCCC;
                                }
                            """
                       
        self.save_animation = QPushButton('Save Animation', self)
        self.save_animation.resize(AnimationToolsPanel.IO_BUTTON_WIDTH, AnimationToolsPanel.HEIGHT)
        self.save_animation.move(AnimationToolsPanel.IO_BLOCK_START_X, AnimationToolsPanel.FRAME_MARGIN)        
        self.save_animation.setStyleSheet(button_stylesheet)
        self.save_animation.clicked.connect(self.saveXML)
       
        self.load_animation = QPushButton('Load Animation', self)
        self.load_animation.resize(AnimationToolsPanel.IO_BUTTON_WIDTH, AnimationToolsPanel.HEIGHT)
        self.load_animation.move(AnimationToolsPanel.IO_BLOCK_START_X + AnimationToolsPanel.IO_BUTTON_WIDTH, AnimationToolsPanel.FRAME_MARGIN)        
        self.load_animation.setStyleSheet(button_stylesheet)
        self.load_animation.clicked.connect(self.fromXML)
        
        self.player = AnimationPlayer(self)
        self.player.move(0, AnimationToolsPanel.FRAME_MARGIN)
        self.player.show()
        
        self.time_input = TimeInputLine(self)
        self.time_input.move(AnimationToolsPanel.TIME_INPUT_X, AnimationToolsPanel.FRAME_WIDTH)
        self.time_input.addAcceptListener(self.onAcceptListener)
        self.time_input.addCancelListener(self.onCancelListener)
        self.time_input.hide()       
        
        self.time_button = QPushButton('', self)
        self.time_button.setIcon(assets.time)
        self.time_button.setIconSize(QSize(AnimationToolsPanel.ICON_SIZE, AnimationToolsPanel.ICON_SIZE))
        self.time_button.resize(AnimationToolsPanel.ICON_BUTTON_WIDTH, AnimationToolsPanel.HEIGHT)
        self.time_button.move(AnimationToolsPanel.BUTTON_BLOCK_X, AnimationToolsPanel.FRAME_MARGIN)        
        self.time_button.setStyleSheet(button_stylesheet)
        self.time_button.clicked.connect(self.timeFrameListener)
        self.time_button.show()        

        self.copy_button = QPushButton('', self)
        self.copy_button.setIcon(assets.copy)
        self.copy_button.setIconSize(QSize(AnimationToolsPanel.ICON_SIZE, AnimationToolsPanel.ICON_SIZE))
        self.copy_button.resize(AnimationToolsPanel.ICON_BUTTON_WIDTH, AnimationToolsPanel.HEIGHT)
        self.copy_button.move(AnimationToolsPanel.BUTTON_BLOCK_X + AnimationToolsPanel.ICON_BUTTON_WIDTH, AnimationToolsPanel.FRAME_MARGIN)        
        self.copy_button.setStyleSheet(button_stylesheet)
        self.copy_button.clicked.connect(self.copyFrameListener)
        self.copy_button.show() 
        
        self.delete_button = QPushButton('', self)
        self.delete_button.setIcon(assets.delete)
        self.delete_button.setIconSize(QSize(AnimationToolsPanel.ICON_SIZE, AnimationToolsPanel.ICON_SIZE))
        self.delete_button.resize(AnimationToolsPanel.ICON_BUTTON_WIDTH, AnimationToolsPanel.HEIGHT)
        self.delete_button.move(AnimationToolsPanel.BUTTON_BLOCK_X + AnimationToolsPanel.ICON_BUTTON_WIDTH*2, AnimationToolsPanel.FRAME_MARGIN)        
        self.delete_button.setStyleSheet(button_stylesheet)
        self.delete_button.clicked.connect(self.deleteListener)
        self.delete_button.show() 
    
    """ Methods to show/hide the input time and frame-control buttons """
    def showButtonBlock(self):
        self.delete_button.show()
        self.time_button.show()
        self.copy_button.show()
        self.time_input.hide()
    def showInputTime(self):
        self.delete_button.hide()
        self.time_button.hide()
        self.copy_button.hide()  
        self.time_input.label.setText(self.tools.framemenu.getActiveFrame()[0].text().split(":")[0] + ":")
        self.time_input.show()
    
    def hideAll(self):
        self.delete_button.hide()
        self.time_button.hide()
        self.copy_button.hide()
        self.time_input.hide()
        self.save_animation.hide()
        self.load_animation.hide()
        self.setFrameShape(QFrame.NoFrame)
    def showAll(self):
        self.showButtonBlock()
        self.save_animation.show()
        self.load_animation.show()
        self.setFrameShape(QFrame.StyledPanel)
    
    """ time change listeners, which are called by the TimeInput component """
    def onCancelListener(self):
        self.showButtonBlock()    
    def onAcceptListener(self):
        time = self.time_input.spinbox.value()
        self.tools.framemenu.changeFrameTime(time)
        self.showButtonBlock()
    
    """ Listeners for delete, copy and time buttons """
    def deleteListener(self):
        self.tools.framemenu.deleteFrame(self)
    def copyFrameListener(self):
        self.tools.framemenu.copyFrame()
    def timeFrameListener(self):    
        active_frame = self.tools.framemenu.getActiveFrame()
        if not active_frame == None:
            self.showInputTime()  
       
    """ listeners for XML binding and parsing """
    def saveXML(self):
        if len(self.tools.framemenu.getAllFrames()) > 1:
            result = QFileDialog.getSaveFileName(self, 'Choose the destination for the animation file!', '.', 'Animation File (*.armo)')
            if result[0] != "":
                XML().toXML(self.tools.framemenu.getAllFrames(), result[0])
        else:
            QMessageBox.information(self, "Stickman Message", "You need at least 2 frames to save the animation!")
        
    def fromXML(self):
        file = QFileDialog.getOpenFileName(self, "Load Animation", ".", "Animation Files (*.armo)")
        if file[0] != "":
            try:
                frames = XML().fromXML(file[0])
                self.tools.framemenu.removeAllFrames()
                for frame in frames:
                    self.tools.framemenu.addNewFrame(frame)
                if len(frames) > 0:
                    getWorld().setWorldFrom(frames[0])
            except:
                QMessageBox.information(self, "Stickman Message", "The animation file is not valid!")
class AnimationPlayer(QFrame):
    
    STOPPED = 0
    PLAYING = 1
    PAUSED = 2 
    
    WIDTH = 260
    
    def __init__(self, parent):
        super().__init__(parent)           
        self.initUI()  
    
    def initUI(self):
        self.resize(AnimationPlayer.WIDTH, AnimationToolsPanel.HEIGHT)
        self.playing = AnimationPlayer.STOPPED
        
        button_stylesheet = """
                                .QPushButton {
                                    font-weight: bold;
                                    font-size: 13px;
                                    background-color:#E0E0E0;
                                }
                                .QPushButton:pressed {
                                    background-color:#CCCCCC;
                                }
                            """
        
        self.play_button = QPushButton('', self)
        self.play_button.setIcon(assets.play)
        self.play_button.setIconSize(QSize(AnimationToolsPanel.ICON_SIZE, AnimationToolsPanel.ICON_SIZE))
        self.play_button.resize(AnimationToolsPanel.ICON_BUTTON_WIDTH, AnimationToolsPanel.HEIGHT)
        self.play_button.move(0, 0)        
        self.play_button.setStyleSheet(button_stylesheet)
        self.play_button.clicked.connect(self.onPlay)
        self.play_button.show()        
        
        self.clock = Clock(self)
        self.clock.move(AnimationToolsPanel.ICON_BUTTON_WIDTH, 0)
        self.clock.task = self.updateAnimation
        self.clock.hide()
        
        self.stop_button = QPushButton('', self)
        self.stop_button.setIcon(assets.stop)
        self.stop_button.setIconSize(QSize(AnimationToolsPanel.ICON_SIZE, AnimationToolsPanel.ICON_SIZE))
        self.stop_button.resize(AnimationToolsPanel.ICON_BUTTON_WIDTH, AnimationToolsPanel.HEIGHT)
        self.stop_button.move(AnimationPlayer.WIDTH - AnimationToolsPanel.ICON_BUTTON_WIDTH, 0)        
        self.stop_button.setStyleSheet(button_stylesheet)
        self.stop_button.clicked.connect(self.onStop)
        self.stop_button.hide() 
        
        self.old_frame = None
        self.current_frame = None  
        self.next_frame = None       
        self.steps = 0          #number of intermediate steps between two frames
        self.step_counter = 0   #number of steps already taken for the interpolation
    
    """ called when the play button is pressed """      
    def onPlay(self):        
        self.disable()
        self.clock.show()
        self.stop_button.show()
        if self.playing == AnimationPlayer.STOPPED: #starting
            self.play_button.setIcon(assets.pause) 
            self.playing = AnimationPlayer.PLAYING                        
            self.play()
        elif self.playing == AnimationPlayer.PAUSED:
            self.play_button.setIcon(assets.pause) 
            self.playing = AnimationPlayer.PLAYING                        
            self.clock.startClock()
        else:                                       #pausing
            self.play_button.setIcon(assets.play) 
            self.playing = AnimationPlayer.PAUSED 
            self.clock.stopClock()        
            
    """ called when the stop button is pressed or the animation is over """                          
    def onStop(self):
        if not self.playing == AnimationPlayer.STOPPED:
            self.enable()
            self.play_button.setIcon(assets.play) 
            self.playing = AnimationPlayer.STOPPED              
            self.clock.stopClock()
            self.clock.reset()
            self.clock.hide()
            self.stop_button.hide()  
    
    """ Methods which enable and disable screen controls while the animation plays """
    def disable(self):
        self.parent().parent().control_panel.setEnabled(False)
        self.parent().parent().canvas.setEnabled(False)
        self.parent().tools.framemenu.hide()
        self.parent().hideAll()
        
    def enable(self):
        self.parent().parent().control_panel.setEnabled(True)
        self.parent().parent().canvas.setEnabled(True)
        self.parent().tools.framemenu.show()
        self.parent().showAll()
    
    """ Entry method for the animation """
    def play(self):
        if self.parent().tools.framemenu.getActiveFrame() == None:
            self.next_frame = self.parent().tools.framemenu.getFirstFrame()
        else:
            self.next_frame = self.parent().tools.framemenu.getActiveFrame()[1]
        if self.next_frame != None:
            self.reloadFrames()
        else:
            self.onStop()
            
    """ this method loads two frames between which it is required to interpolate.
        It loads frames from the FrameList until there are no more pairs of frames """
    def reloadFrames(self):
        self.clock.stopClock()
        
        self.old_frame = self.next_frame        
        self.current_frame = self.old_frame.copy()
        getWorld().setWorldFrom(self.current_frame)        
        self.next_frame = self.parent().tools.framemenu.getNextFrame(self.old_frame)
        
        if self.next_frame != None:            
            self.steps = (self.next_frame.time*1000)/Clock.TIMER_STEP
            self.step_counter = 0
            self.clock.startClock()
        else:
            self.onStop()
    
    """ Methods used to perform the interpolation job as they are """
    def updateAnimation(self):
        if self.step_counter < self.steps:
            self.step_counter = self.step_counter + 1            
            step_ratio = self.step_counter/self.steps            
            # interpolate all stickmen one by one
            for stickman in self.old_frame.stickmen:                
                new_stickman = self.next_frame.getStickman(stickman.name)                
                # need to check the new stickman, because it can be removed in the next frame
                if new_stickman != None:
                    self.interpolatePosition(stickman, new_stickman, step_ratio)
                    self.interpolateJoints(stickman, new_stickman, step_ratio)        
        else:
            self.reloadFrames()    # called when two frames have interpolated enough to swap the last approximation for the real next frame
    
    """ Interpolates between the positions of stickman body """
    def interpolatePosition(self, old_stickman, new_stickman, ratio):
        x_difference = new_stickman.x - old_stickman.x
        y_difference = new_stickman.y - old_stickman.y
        current_x = x_difference*ratio
        current_y = y_difference*ratio
                    
        modified_stickman = self.current_frame.getStickman(old_stickman.name)
        modified_stickman.x = old_stickman.x + current_x
        modified_stickman.y = old_stickman.y + current_y
    
    """ Interpolates between the positions of stickman joints """
    def interpolateJoints(self, old_stickman, new_stickman, ratio):
        i = 0
        while i < len(old_stickman.joints):
            old_joint = old_stickman.joints[i]
            new_joint = new_stickman.joints[i]                       
                        
            if (old_joint.attachment != None and new_joint.attachment != None):
                # degree difference and its alternatives are used to calculate the shortes path in rotation between two points of stickman
                degree_difference = new_joint.angle - old_joint.angle
                degree_difference_alternative = (2*math.pi - old_joint.angle + new_joint.angle)
                if abs(degree_difference) <= abs(degree_difference_alternative):
                    current_degree_change = degree_difference*ratio
                else:
                    current_degree_change = degree_difference_alternative*ratio
                
                modified_stickman = self.current_frame.getStickman(old_stickman.name)
                degree_by = old_joint.angle + current_degree_change - modified_stickman.joints[i].angle                        
                modified_stickman.joints[i].rotateBy(degree_by)                
            i = i + 1  
Exemplo n.º 33
0
class SettingChildWin(QDialog):
    height_ = 25

    def __init__(self, *args, **kwargs):
        super().__init__(*args)
        self.allModeGroup = QButtonGroup(self)
        self.npkModeGroup = QButtonGroup(self)
        if "mainWin" in kwargs.keys():
            self.mainWin = kwargs["mainWin"]
        self.setObjectName("settingWin")
        self.setUi()
        self.npkModeBox()
        self.allExtractBox()
        self.checkBox()
        self.saveDirSelectBtn()
        self.img2DirBtn()
        self.portBtn = self.testPortBtn()
        self.inputPort()
        self.hide()

    def setUi(self):
        self.setFixedSize(400, 220)
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowTitle("设置")

    # 0
    def npkModeBox(self):
        label_ = QLabel(self)
        label_.resize(self.width() // 3, 25)
        label_.setText("NPK提取模式:")
        label_.setAlignment(Qt.AlignCenter)
        label_.setStyleSheet("font-size: 15px")
        # 选项AB
        npkYes = QRadioButton(self)
        npkYes.resize(self.width() // 3, 25)
        npkYes.move(self.width() // 3, 0)
        npkYes.setText("提取")
        npkNo = QRadioButton(self)
        npkNo.resize(self.width() // 3, 25)
        npkNo.move(self.width() // 3 * 2, 0)
        npkNo.setText("不提取")
        npkNo.setChecked(True)

        def npkYesFunc():
            if not self.mainWin.npkDict:
                QMessageBox.warning(self, "未设置NPK词典", "未设置NPK词典将不能设置NPK提取",
                                    QMessageBox.Yes, QMessageBox.Yes)
                npkNo.setChecked(True)
                return False
            if not self.mainWin.img2Dir:
                QMessageBox.warning(self, "未设置img2目录", "未设置img2目录将不能设置NPK提取",
                                    QMessageBox.Yes, QMessageBox.Yes)
                npkNo.setChecked(True)
                return False

        npkYes.clicked.connect(npkYesFunc)

        def yes():
            self.mainWin.npkMode = True

        npkYes.toggled.connect(yes)

        def no():
            self.mainWin.npkMode = False

        npkNo.toggled.connect(no)
        self.npkModeGroup.setObjectName("npkExtractMode")
        self.npkModeGroup.addButton(npkYes)
        self.npkModeGroup.addButton(npkNo)

    # 1
    def allExtractBox(self):
        label_ = QLabel(self)
        label_.resize(self.width() // 3, 25)
        label_.move(0, 25)
        label_.setText("全部提取模式:")
        label_.setAlignment(Qt.AlignCenter)
        label_.setStyleSheet("font-size: 15px")
        # 选项AB
        allYes = QRadioButton(self)
        allYes.resize(self.width() // 3, 25)
        allYes.move(self.width() // 3, 25)
        allYes.setText("全部提取")
        allNo = QRadioButton(self)
        allNo.resize(self.width() // 3, 25)
        allNo.move(self.width() // 3 * 2, 25)
        allNo.setText("单个提取")
        allNo.setChecked(True)

        self.allModeGroup.setObjectName("allExtractMode")
        self.allModeGroup.addButton(allYes)
        self.allModeGroup.addButton(allNo)

    # def setImg2Dir(self):
    # 2
    def saveDirSelectBtn(self):
        btn = QPushButton("保存文件夹", self)
        btn.setObjectName("saveDirSelectBtn")
        btn.resize(self.width() / 2, self.height_)
        btn.move(0, self.height_ * 2)

        # btn.setStyleSheet("background-color: pink")

        def btnFunc():
            saveDirFunc(self)

        btn.clicked.connect(btnFunc)

    def img2DirBtn(self):
        btn = QPushButton("ImagePacks2文件夹", self)
        btn.setObjectName("saveDirSelectBtn")
        btn.resize(self.width() / 2, self.height_)
        btn.move(self.width() / 2, self.height_ * 2)

        # btn.setStyleSheet("background-color: pink")

        def btnFunc():
            if img2DirFunc(self) is False:
                QMessageBox.warning(self, "img2文件夹选择错误", "文件夹下无NPK文件,请重新选择",
                                    QMessageBox.Yes, QMessageBox.Yes)

        btn.clicked.connect(btnFunc)

    # 3
    def testPortBtn(self):
        portBtn = QPushButton("默认端口测试", self)
        portBtn.setObjectName("testPortBtn")
        portBtn.resize((self.width() - 30) / 2, self.height_)
        portBtn.move(0, self.height_ * 3)

        # portBtn.setEnabled(False)

        def portBtnFunc():
            testPortFunc(self)

        portBtn.clicked.connect(portBtnFunc)
        return portBtn

    # 3
    def inputPort(self):
        self.checkPort = QPushButton("√", self)
        self.checkPort.resize(30, self.height_)
        self.checkPort.move(self.width() - 30, self.height_ * 3)
        # self.checkPort.hide()

        self.inputLine = QLineEdit("输入端口", self)
        self.inputLine.resize((self.width() - 30) / 2, 25)
        self.inputLine.move((self.width() - 30) / 2, 25 * 3)

        # self.inputLine.hide()

        def inputPortF():
            self.mainWin.port = self.inputLine.text()
            self.portBtn.click()

        self.checkPort.clicked.connect(inputPortF)

    def checkBox(self):
        #
        confirmBtn = QPushButton("确认", self)
        confirmBtn.resize(self.width() // 2, 25)
        confirmBtn.move(0, self.height() - 25)
        confirmBtn.clicked.connect(self.hide)
        #
        cancelBtn = QPushButton("取消", self)
        cancelBtn.resize(self.width() // 2, 25)
        cancelBtn.move(self.width() // 2, self.height() - 25)
        cancelBtn.clicked.connect(self.close)

    def closeEvent(self, closeEvt):
        reply = QMessageBox.question(self, "", "关闭后,设置将不会保存", QMessageBox.Yes,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            for button in self.checkedList:
                button.setChecked(True)
            self.hide()
        else:
            closeEvt.ignore()

    def showEvent(self, showEvt):
        self.checkedList = [
            group.checkedButton() for group in self.findChildren(QButtonGroup)
        ]
        return super().showEvent(showEvt)
Exemplo n.º 34
0
class InputLine(QWidget):
    
    HEIGHT = 30
    LABEL_WIDTH = 170
    INPUT_TEXT_WIDTH = 200
    BUTTON_WIDTH = 100
    BUTTON_BLOCK_X = 380
    ELEMENT_GAP = 5
    
    ERROR_WIDTH = 250
    ERROR_X = 595
    
    def __init__(self, parent):
        super().__init__(parent)
        self.initUI()
        
    def initUI(self):
                
        component_stylesheet = """
                                .QPushButton {
                                    font-weight: bold;
                                    font-size: 13px;
                                    background-color:#E0E0E0;
                                }
                                .QPushButton:pressed {
                                    background-color:#CCCCCC;
                                }
                                .QLabel {
                                    padding-top: 7px;
                                    font-weight: bold;
                                    font-size: 14px;
                                }
                                .QLineEdit {
                                    font-weight: bold;
                                    font-size: 14px;
                                }
                                .QLabel#error {
                                    color: red;
                                    font-size: 12px;
                                    font-style: italic;
                                    padding-top: 0px;
                                    padding-left: 6px;
                                }   
                            """       
               
        self.label = QLabel("", self)
        self.label.setStyleSheet(component_stylesheet)
        self.label.setAlignment(Qt.AlignRight)
        self.label.resize(InputLine.LABEL_WIDTH, InputLine.HEIGHT)
        self.label.move(0, 0)        
        
        self.text = QLineEdit(self)
        self.text.setStyleSheet(component_stylesheet)
        self.text.resize(InputLine.INPUT_TEXT_WIDTH, InputLine.HEIGHT)
        self.text.move(InputLine.LABEL_WIDTH + InputLine.ELEMENT_GAP, 0)
        
        self.ok = QPushButton("OK", self)
        self.ok.setStyleSheet(component_stylesheet)
        self.ok.resize(InputLine.BUTTON_WIDTH, InputLine.HEIGHT)
        self.ok.move(InputLine.BUTTON_BLOCK_X, 0)
        
        self.cancel = QPushButton("Cancel", self)
        self.cancel.setStyleSheet(component_stylesheet)
        self.cancel.resize(InputLine.BUTTON_WIDTH, InputLine.HEIGHT)
        self.cancel.move(InputLine.BUTTON_BLOCK_X + InputLine.BUTTON_WIDTH + InputLine.ELEMENT_GAP, 0)
    
        self.error = QLabel("", self)
        self.error.setObjectName("error")
        self.error.setStyleSheet(component_stylesheet)
        self.error.resize(InputLine.ERROR_WIDTH, InputLine.HEIGHT)
        self.error.move(InputLine.ERROR_X, 0)
    
    """ listeners which control what happens on ok an cancel button presses """
    def addOkListener(self, onOkEvent):
        self.ok.clicked.connect(onOkEvent)
    def addCancelListener(self, onCancelEvent):
        self.cancel.clicked.connect(onCancelEvent)
        
    """ utility methods of the widget """
    def getText(self):
        return self.text.text()
    def setText(self, text):
        self.text.setText(text)        
        
    def setLabelText(self, text):
        self.label.setText(text)
        
    def setErrorText(self, text):
        self.error.setText(text)
Exemplo n.º 35
0
class TimeInputLine(QFrame):
    
    WIDTH = 396
    HEIGHT = 43
    
    FRAME_WIDTH = 1
    FRAME_MARGIN = 2
    
    ICON_SIZE = 35
    ICON_BUTTON_WIDTH = 60    
    
    LABEL_SIZE_X = 174
    INPUT_SIZE_X = 100
    BUTTON_BLOCK_X = 278
    
    STEP = 0.5
    MIN_VALUE = 0.1
    MAX_VALUE = 10
    DECIMAL_COUNT = 1
    
    def __init__(self, parent):
        super().__init__(parent)
        self.initUI()       
    
    def initUI(self):
        self.resize(TimeInputLine.WIDTH + TimeInputLine.FRAME_MARGIN*2, TimeInputLine.HEIGHT + TimeInputLine.FRAME_MARGIN*2)
        self.setFrameStyle(QFrame.StyledPanel)
        self.setLineWidth(TimeInputLine.FRAME_WIDTH)
        
        component_stylesheet = """
                                .QPushButton {
                                    font-weight: bold;
                                    font-size: 13px;
                                    background-color:#E0E0E0;
                                }
                                .QPushButton:pressed {
                                    background-color:#CCCCCC;
                                }
                                .QDoubleSpinBox {
                                    font-weight: bold;
                                    font-size: 23px;
                                }
                                .QLabel {
                                    font-weight: bold;
                                    font-size: 23px;
                                }
                            """
        
        self.label = QLabel("", self)
        self.label.resize(TimeInputLine.LABEL_SIZE_X, TimeInputLine.HEIGHT)
        self.label.move(TimeInputLine.FRAME_MARGIN, TimeInputLine.FRAME_MARGIN)
        self.label.setStyleSheet(component_stylesheet)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.show()       
        
        self.spinbox = QDoubleSpinBox(self)
        self.spinbox.setRange(TimeInputLine.MIN_VALUE, TimeInputLine.MAX_VALUE)
        self.spinbox.setValue(TimeInputLine.STEP)
        self.spinbox.setSingleStep(TimeInputLine.STEP)
        self.spinbox.setDecimals(TimeInputLine.DECIMAL_COUNT)
        self.spinbox.resize(TimeInputLine.INPUT_SIZE_X, TimeInputLine.HEIGHT)
        self.spinbox.move(TimeInputLine.LABEL_SIZE_X + TimeInputLine.FRAME_MARGIN, TimeInputLine.FRAME_MARGIN)
        self.spinbox.setStyleSheet(component_stylesheet)
        self.spinbox.show()
        
        self.enter = QPushButton("", self)
        self.enter.setIcon(assets.enter)
        self.enter.setIconSize(QSize(TimeInputLine.ICON_SIZE, TimeInputLine.ICON_SIZE))
        self.enter.resize(TimeInputLine.ICON_BUTTON_WIDTH, TimeInputLine.HEIGHT)
        self.enter.move(TimeInputLine.BUTTON_BLOCK_X, TimeInputLine.FRAME_MARGIN)  
        self.enter.setStyleSheet(component_stylesheet)
        self.enter.show()
        
        self.cancel = QPushButton("", self)
        self.cancel.setIcon(assets.exit)
        self.cancel.setIconSize(QSize(TimeInputLine.ICON_SIZE, TimeInputLine.ICON_SIZE))
        self.cancel.resize(TimeInputLine.ICON_BUTTON_WIDTH, TimeInputLine.HEIGHT)
        self.cancel.move(TimeInputLine.BUTTON_BLOCK_X + TimeInputLine.ICON_BUTTON_WIDTH, TimeInputLine.FRAME_MARGIN)     
        self.cancel.setStyleSheet(component_stylesheet) 
        self.cancel.show()
    
    """ listeners which control what happens on accept and on cancel button presses """
    def addAcceptListener(self, onAcceptListener):
        self.enter.clicked.connect(onAcceptListener)
    def addCancelListener(self, onCancelListener):
        self.cancel.clicked.connect(onCancelListener)   
Exemplo n.º 36
0
class SingleRank(QWidget):
    single_rk_comeback_sg = pyqtSignal()
    detail_sg = pyqtSignal(str)

    def __init__(self, parent=None):
        super(SingleRank, self).__init__(parent)
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.h = self.screenRect.height()
        self.w = self.screenRect.width()
        self.xr = self.w / 930
        self.yr = self.h / 640
        self.zr = min(self.xr, self.yr)
        self.inlist = {}
        self.back2_wi = QWidget(self)
        self.rankexit_but = QPushButton(self)
        self.header1 = QLabel(self.back2_wi)
        self.comeback_but = QPushButton(self.back2_wi)
        self.next_but = QPushButton(self.back2_wi)
        self.table = QWidget(self.back2_wi)
        self.tablein = QGridLayout()
        self.headers = ['对局id', '分数', '时间', '详情']
        self.set_ui()
        with open('rank.qss', 'r') as f:
            self.setStyleSheet(f.read())

    def set_ui(self):
        self.setWindowTitle('SingleRank')
        self.setObjectName('singlerank')
        self.resize(self.w, self.h)
        effect = QGraphicsDropShadowEffect()
        effect.setOffset(10, 10)
        effect.setColor(QColor(0, 0, 0, 80))
        effect.setBlurRadius(20)
        effect1 = QGraphicsDropShadowEffect()
        effect1.setOffset(10, 10)
        effect1.setColor(QColor(0, 0, 0, 80))
        effect1.setBlurRadius(20)
        self.back2_wi.setObjectName('back')
        self.back2_wi.resize(self.xr * 793, self.yr * 534)
        self.back2_wi.move(self.xr * 69, self.yr * 53)
        self.back2_wi.setGraphicsEffect(effect)
        self.header1.setObjectName('header')
        self.header1.resize(self.xr * 172, self.yr * 36)
        self.header1.move(self.xr * 24, self.yr * 10)
        self.header1.setText('过往战绩')
        self.header1.setAlignment(Qt.AlignCenter)
        self.comeback_but.setObjectName('comeback')
        self.comeback_but.resize(self.xr * 80, self.yr * 36)
        self.comeback_but.move(self.xr * 67, self.yr * 467)
        self.comeback_but.setText('返回')
        self.comeback_but.clicked.connect(self.come_back)
        self.comeback_but.setGraphicsEffect(effect1)
        self.next_but.setObjectName('next')
        self.next_but.resize(self.zr * 38, self.zr * 38)
        self.next_but.move(self.xr * 725, self.yr * 468)
        self.next_but.setStyleSheet('border-radius:{}px;'.format(self.zr * 18))
        self.next_but.clicked.connect(self.next)
        self.table.setObjectName('table')
        self.table.resize(self.xr * 746, self.yr * 382)
        self.table.move(self.xr * 24, self.yr * 61)
        self.tablein.setSpacing(0)
        self.tablein.setContentsMargins(0, 0, 0, 0)
        self.table.setLayout(self.tablein)
        li = ['#f5f0e3', '#cccccc']
        for i in range(0, 5):
            for j in range(0, 4):
                if j == 3 and i != 0:
                    exec('self.tableheader{}_{} = QPushButton()'.format(i, j))
                    exec(
                        'self.tableheader{}_{}.setMinimumHeight(self.yr *382/5)'
                        .format(i, j))
                    exec('self.tableheader{}_{}.setText("详情")'.format(i, j))
                    exec(
                        'self.tableheader{}_{}.clicked.connect(self.details{})'
                        .format(i, j, i))
                else:
                    exec('self.tableheader{}_{} = QLabel()'.format(i, j))
                    exec('self.tableheader{}_{}.setAlignment(Qt.AlignCenter)'.
                         format(i, j))
                if i == 0:
                    exec('self.tableheader{}_{}.setObjectName("table_head")'.
                         format(i, j))
                    exec('self.tableheader{}_{}.setText("{}")'.format(
                        i, j, self.headers[j]))
                else:
                    exec('self.tableheader{}_{}.setObjectName("table_unit")'.
                         format(i, j))
                exec(
                    'self.tableheader{}_{}.setStyleSheet("background-color:{};")'
                    .format(i, j, li[(i + j) % 2]))
                exec('self.tablein.addWidget(self.tableheader{}_{}, {}, {})'.
                     format(i, j, i, j))
        self.back2_wi.setStyleSheet('#back{border-radius:' +
                                    str(self.zr * 20) +
                                    'px;}#header{border-radius:' +
                                    str(self.zr * 15) + 'px;font-size:' +
                                    str(int(self.zr * 18)) +
                                    'px;}#comeback{border-radius:' +
                                    str(self.zr * 15) + 'px;font-size:' +
                                    str(int(self.zr * 16)) +
                                    'px;}#table_unit{font-size:' +
                                    str(int(self.zr * 18)) +
                                    'px;}#table_head{font-size:' +
                                    str(int(self.zr * 20)) +
                                    'px;font-weight:bold}')

    def come_back(self):
        self.single_rk_comeback_sg.emit()

    def get_list(self, info):
        if len(info) >= 4:
            li = info[:4]
            self.inlist = info[4:]
        else:
            li = info
            self.inlist = info
        self.set_table(li)

    def set_table(self, mp):
        lens = len(mp)
        for i in range(1, lens + 1):
            self.next_but.setEnabled(True)
            exec('self.tableheader{}_0.setText("{}")'.format(
                i, mp[i - 1]['id']))
            exec('self.tableheader{}_1.setText("{}")'.format(
                i, mp[i - 1]['score']))
            exec('self.tableheader{}_2.setText("{}")'.format(
                i, mp[i - 1]['time']))
        if lens < 4:
            for i in range(lens + 1, 5):
                self.next_but.setEnabled(False)
                exec('self.tableheader{}_0.clear()'.format(i))
                exec('self.tableheader{}_1.clear()'.format(i))
                exec('self.tableheader{}_2.clear()'.format(i))

    def next(self):
        if len(self.inlist) >= 4:
            li = self.inlist[:4]
            self.inlist = self.inlist[4:]
        else:
            li = self.inlist
        self.set_table(li)

    def details1(self):
        if self.tableheader1_0.text() != '':
            self.detail_sg.emit(self.tableheader1_0.text())

    def details2(self):
        if self.tableheader2_0.text() != '':
            self.detail_sg.emit(self.tableheader2_0.text())

    def details3(self):
        if self.tableheader3_0.text() != '':
            self.detail_sg.emit(self.tableheader3_0.text())

    def details4(self):
        if self.tableheader4_0.text() != '':
            self.detail_sg.emit(self.tableheader4_0.text())
Exemplo n.º 37
0
 def create_widgets(self):
     btn = QPushButton('Button', self)
     btn.setToolTip('This is <b>QPushButton</b> widget')
     btn.resize(btn.sizeHint())
     btn.move(50, 50)
Exemplo n.º 38
0
class Game(QWidget):
    def __init__(self):
        super().__init__()
        self._flag_1 = False
        self.media = QtCore.QUrl.fromLocalFile("MP3/music.mp3")
        content = QtMultimedia.QMediaContent(self.media)
        self.player = QtMultimedia.QMediaPlayer()
        self.player.setMedia(content)
        self.player.setVolume(50)
        self.initUI()

    def initUI(self):
        self.file_number = 2
        self._score = 0
        self.setMouseTracking(True)
        self.resize(500, 500)
        self.center()
        self.setWindowTitle('Игра')

        self.main_pic = QLabel(self)
        self.main_pic.setPixmap(
            QPixmap(resource_path("PIC/running_rabbit.jpg")))
        self.main_pic.resize(500, 500)

        self.button_start_game = QPushButton("НАЧАТЬ ИГРУ", self)
        self.button_start_game.resize(140, 50)
        self.button_start_game.move(70, 300)
        self.button_start_game.clicked.connect(self.start_game)

        self.button_edit_map = QPushButton("СОЗДАТЬ КАРТУ", self)
        self.button_edit_map.resize(140, 50)
        self.button_edit_map.move(70, 360)
        self.button_edit_map.clicked.connect(self.edit_map_menu)

        self.button_exit = QPushButton("ЗАКОНЧИТЬ СЕАНС", self)
        self.button_exit.resize(140, 50)
        self.button_exit.move(70, 420)
        self.button_exit.clicked.connect(self.exit)

        self.timer_game = QTimer()
        self.timer_game.timeout.connect(self.updateValues)
        self.timer_game.start(200)
        self.setFocusPolicy(Qt.StrongFocus)

        self.lable_score = QLabel(self)
        self.lable_score.resize(200, 35)
        self.lable_score.setFont(
            QFont("RetroComputer[RUS by Daymarius]", 26, QFont.Bold))
        self.lable_score.setVisible(False)

        self.button_menu = QPushButton("НАЗАД", self)
        self.button_menu.resize(120, 40)
        self.button_menu.clicked.connect(self.show_menu)
        self.button_menu.setVisible(False)

        self.lable_name = QLabel("ВВЕДИТЕ ВАШЕ ИМЯ:", self)
        self.lable_name.sizeHint()
        self.lable_name.setFont(
            QFont("RetroComputer[RUS by Daymarius]", 10, QFont.Bold))
        self.lable_name.move(230, 300)

        self.input_name = QLineEdit("Без имени", self)
        self.input_name.resize(200, 20)
        self.input_name.move(230, 325)

        self.table_score = QTableWidget(self)
        self.table_score.resize(200, 120)
        self.table_score.move(230, 350)

    def bd_score(self):
        con = sqlite3.connect(resource_path("DB/score.db"))
        # Создание курсора
        cur = con.cursor()
        # Выполнение запроса и получение всех результатов
        result = cur.execute(
            "SELECT * FROM main ORDER BY score DESC;").fetchmany(5)
        cur.execute("DROP TABLE main")
        cur.execute("CREATE TABLE main (name STRING, score INTEGER)")
        for item in result:
            cur.execute("INSERT INTO main VALUES(?, ?)", (item[0], item[1]))
            con.commit()
        # Вывод результатов на экран
        if result != []:
            self.table_score.setColumnCount(len(result[0]))
            self.table_score.setRowCount(0)
            for i, row in enumerate(result):
                self.table_score.setRowCount(self.table_score.rowCount() + 1)
                for j, elem in enumerate(row):
                    item = QTableWidgetItem(str(elem))
                    self.table_score.setItem(i, j, item)
                    item.setFlags(QtCore.Qt.ItemIsEnabled)
            self.table_score.setHorizontalHeaderItem(
                0, QTableWidgetItem("Имя игрока"))
            self.table_score.setHorizontalHeaderItem(1,
                                                     QTableWidgetItem("Счет"))
            self.table_score.setColumnWidth(0, 127)
            self.table_score.setColumnWidth(1, 20)
        con.close()

    def append_bd_score_and_name(self):
        con = sqlite3.connect("DB/score.db")
        # Создание курсора
        cur = con.cursor()
        cur.execute("INSERT INTO main VALUES(?, ?)",
                    (self.input_name.text(), self.get_score()))
        con.commit()
        self.bd_score()
        con.close()

    def get_score(self):
        return self._score

    def set_score(self, score):
        self._score = score

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Right:
            self.hero.go_right()
        elif event.key() == Qt.Key_Left:
            self.hero.go_left()
        elif event.key() == Qt.Key_Up:
            self.hero.go_up()
        elif event.key() == Qt.Key_Down:
            self.hero.go_down()
        elif event.key() == Qt.Key_Space:
            self.hero.go_dig()

    def keyReleaseEvent(self, QKeyEvent):
        if self._flag_1 and not QKeyEvent.isAutoRepeat():
            self.hero.stop()

    def edit_map_menu(self):
        game.setVisible(False)
        edit_map.create_map()
        edit_map.show()

    def exit(self):
        sys.exit(app.exec())

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def reload_game(self):
        score = self.get_score()
        lifes = self.hero.get_lifes()
        self.start_game()
        self.set_score(score)
        self.hero.set_lifes(lifes)

    def start_game(self):
        self.player.play()
        self.set_score(0)
        self.map = Map(resource_path("MAP/" + str(self.file_number) + ".map"))
        for enemy in self.enemies:
            enemy.create_labirint()
        self.button_menu.setVisible(True)
        self.button_menu.setFocusPolicy(False)
        self.lable_score.setVisible(True)
        self.lable_score.move(0, 0)
        self.button_menu.move(self.map.get_col() * 40 - 120, 0)
        self.lable_score.setText("00000")
        sp_0_1 = []
        for j in range(self.map.get_row()):
            for i in range(self.map.get_col()):
                if type(self.map.get_elem_xy(i, j)) == Empty and (
                        self.map.get_row() - 1 == j
                        or type(self.map.get_elem_xy(
                            i, j + 1)) in [Stairs, Brick]):
                    sp_0_1.append((i, j))

        zerro = Zerro()
        one = One()
        for i in range(int(round(len(sp_0_1) * 0.2))):
            t = randrange(0, len(sp_0_1))
            x, y = sp_0_1[t]
            self.map.set_elem_xy(x, y, choice([zerro, one]))
            del sp_0_1[t]
        self.hide_menu()

    def show_menu(self):
        self.append_bd_score_and_name()
        game.player.pause()
        self.hero.timer.stop()
        for enemy in self.enemies:
            enemy.timer.stop()
        self.timer_game.stop()
        self.main_pic.show()
        self.table_score.show()
        self.input_name.show()
        self.lable_name.show()
        self.button_menu.setVisible(False)
        self.lable_score.setVisible(False)
        self.button_edit_map.setVisible(True)
        self.button_exit.setVisible(True)
        self.button_start_game.setVisible(True)
        self.resize(500, 500)
        self.center()
        self._flag_1 = False

    def hide_menu(self):
        game.player.play()
        self.hero.timer.start(200)
        for enemy in self.enemies:
            enemy.timer.start(200)
        game.timer_game.start(200)
        self.main_pic.hide()
        self.table_score.hide()
        self.input_name.hide()
        self.lable_name.hide()
        self.button_menu.setVisible(True)
        self.lable_score.setVisible(True)
        self.button_edit_map.setVisible(False)
        self.button_exit.setVisible(False)
        self.button_start_game.setVisible(False)
        self.resize(self.map.get_col() * 40, self.map.get_row() * 40 + 40)
        self.center()
        self._flag_1 = True

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        if self._flag_1:
            for i in range(self.map.get_col()):
                for j in range(self.map.get_row()):
                    qp.drawPixmap(
                        i * 40, j * 40 + 40,
                        self.map.get_elem_xy(
                            i, j).get_pic())  # рисуем картинками из elem_map
            qp.drawPixmap(self.hero.get_x() * 40,
                          self.hero.get_y() * 40 + 40, self.hero.get_pic())
            for enemy in self.enemies:
                qp.drawPixmap(enemy.get_x() * 40,
                              enemy.get_y() * 40 + 40, enemy.get_pic())
            for i in range(game.hero.get_lifes()):
                qp.drawPixmap(280 + i * 40, 0,
                              self.hero._pic[self.hero._STOP][0])

            txt = "00000" + str(self._score)
            self.lable_score.setText(txt[len(txt) - 5:len(txt)])
        qp.end()

    def updateValues(self):
        self.update()

    def you_lose(self):
        self.player.pause()
        self.hero.timer.stop()
        for enemy in self.enemies:
            enemy.timer.stop()
        self.timer_game.stop()
        if self.hero.get_lifes() > 1:
            game.player.pause()
            buttonReply = QMessageBox.question(
                self, 'ВЫ ПРОИГРАЛИ', "Продолжить игру?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            if buttonReply == QMessageBox.Yes:
                self.hero.set_lifes(self.hero.get_lifes() - 1)
                self.reload_game()
                self.timer_game.start(200)
            else:
                self.set_score(0)
                self.show_menu()
        else:
            game.player.pause()
            buttonReply = QMessageBox.information(self, 'ИГРА ОКОНЧЕНА',
                                                  "Вы проиграли.")
            self.append_bd_score_and_name()
            self.show_menu()
Exemplo n.º 39
0
    def initUI3(self):

        grid = QGridLayout(self)
        self.setLayout(grid)

        text2 = QLabel('Hostile Ai difficulty')
        text3 = QLabel('Player Ai')

        self.errorLabel1 = QLabel(self)
        self.errorLabel2 = QLabel(self)
        self.errorLabel3 = QLabel(self)

        self.status = QLabel(self)

        self.errorLabel1.setText("Error status\n" + str(self.error[0]))
        self.errorLabel2.setText("Error status\n" + str(self.error[1]))
        self.errorLabel3.setText("Error status\n" + str(self.error[2]))

        self._togglep1 = True
        self.playerOne = QCheckBox('Player 1 is human', self)
        self.playerOne.toggle()
        self.playerOne.clicked.connect(self.togglep1)
        self.playerOneAi = QCheckBox('Player 1 is AI', self)
        self.playerOneAi.clicked.connect(self.togglep1)

        self._togglep2 = True
        self.playerTwo = QCheckBox('Player 2 is human', self)
        self.playerTwo.toggle()
        self.playerTwo.clicked.connect(self.togglep2)
        self.playerTwoAi = QCheckBox('Player 2 is AI', self)
        self.playerTwoAi.clicked.connect(self.togglep2)
        self.playerTwo.setDisabled(True)
        self.playerTwoAi.setDisabled(True)

        self._togglep3 = True
        self.playerThree = QCheckBox('Player 3 is human', self)
        self.playerThree.toggle()
        self.playerThree.clicked.connect(self.togglep3)
        self.playerThreeAi = QCheckBox('Player 3 is AI', self)
        self.playerThreeAi.clicked.connect(self.togglep3)
        self.playerOneAi.setDisabled(True)
        self.playerOne.setDisabled(True)
        cancelButton = QPushButton('Done', self)

        self.difAi1 = QLineEdit(self)
        self.difAi1.setText("1")
        self.difAi1.textChanged[str].connect(self.TextChengedAi1)
        self.difPl1 = QLineEdit(self)
        self.difPl1.setText("1")
        self.difPl1.textChanged[str].connect(self.TextChengedPl1)
        self.difAi2 = QLineEdit(self)
        self.difAi2.setText("1")
        self.difAi2.setReadOnly(True)
        self.difAi2.textChanged[str].connect(self.TextChengedAi2)
        self.difPl2 = QLineEdit(self)
        self.difPl2.setText("1")
        self.difPl2.setReadOnly(True)
        self.difPl2.textChanged[str].connect(self.TextChengedPl2)
        self.difAi3 = QLineEdit(self)
        self.difAi3.setText("1")
        self.difAi1.setReadOnly(True)
        self.difAi3.textChanged[str].connect(self.TextChengedAi3)
        self.difPl3 = QLineEdit(self)
        self.difPl3.setText("1")
        self.difPl1.setReadOnly(True)
        self.difPl3.textChanged[str].connect(self.TextChengedPl3)

        cancelButton.clicked.connect(self.Close)
        cancelButton.move(60, 20)
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('QCheckBox')

        grid.addWidget(text2, 3, 0)
        grid.addWidget(text3, 4, 0)

        grid.addWidget(self.status, 0, 2)

        grid.addWidget(self.playerOne, 1, 1)
        grid.addWidget(self.playerOneAi, 2, 1)
        grid.addWidget(self.playerTwo, 1, 2)
        grid.addWidget(self.playerTwoAi, 2, 2)
        grid.addWidget(self.playerThree, 1, 3)
        grid.addWidget(self.playerThreeAi, 2, 3)

        grid.addWidget(cancelButton, 0, 3)

        grid.addWidget(self.difAi1, 4, 1)
        grid.addWidget(self.difPl1, 3, 1)
        grid.addWidget(self.difAi2, 4, 2)
        grid.addWidget(self.difPl2, 3, 2)
        grid.addWidget(self.difAi3, 4, 3)
        grid.addWidget(self.difPl3, 3, 3)

        grid.addWidget(self.errorLabel1, 5, 1)
        grid.addWidget(self.errorLabel2, 5, 2)
        grid.addWidget(self.errorLabel3, 5, 3)

        grid
        self.show()