diff options
Diffstat (limited to 'examples/widgets/widgets')
-rw-r--r-- | examples/widgets/widgets/charactermap/charactermap.pyproject | 4 | ||||
-rw-r--r-- | examples/widgets/widgets/charactermap/characterwidget.py | 133 | ||||
-rw-r--r-- | examples/widgets/widgets/charactermap/doc/charactermap.rst | 8 | ||||
-rw-r--r-- | examples/widgets/widgets/charactermap/fontinfodialog.py | 47 | ||||
-rw-r--r-- | examples/widgets/widgets/charactermap/main.py | 17 | ||||
-rw-r--r-- | examples/widgets/widgets/charactermap/mainwindow.py | 167 | ||||
-rw-r--r-- | examples/widgets/widgets/digitalclock/digitalclock.py | 41 | ||||
-rw-r--r-- | examples/widgets/widgets/digitalclock/digitalclock.pyproject | 3 | ||||
-rw-r--r-- | examples/widgets/widgets/digitalclock/doc/digitalclock-screenshot.png | bin | 0 -> 726 bytes | |||
-rw-r--r-- | examples/widgets/widgets/digitalclock/doc/digitalclock.rst | 14 | ||||
-rw-r--r-- | examples/widgets/widgets/tetrix/doc/tetrix-screenshot.png | bin | 0 -> 5396 bytes | |||
-rw-r--r-- | examples/widgets/widgets/tetrix/doc/tetrix.rst | 38 | ||||
-rw-r--r-- | examples/widgets/widgets/tetrix/tetrix.py | 472 | ||||
-rw-r--r-- | examples/widgets/widgets/tetrix/tetrix.pyproject | 3 |
14 files changed, 947 insertions, 0 deletions
diff --git a/examples/widgets/widgets/charactermap/charactermap.pyproject b/examples/widgets/widgets/charactermap/charactermap.pyproject new file mode 100644 index 000000000..c2b2c2068 --- /dev/null +++ b/examples/widgets/widgets/charactermap/charactermap.pyproject @@ -0,0 +1,4 @@ +{ + "files": ["main.py", "characterwidget.py", "fontinfodialog.py", + "mainwindow.py"] +} diff --git a/examples/widgets/widgets/charactermap/characterwidget.py b/examples/widgets/widgets/charactermap/characterwidget.py new file mode 100644 index 000000000..0f01f9684 --- /dev/null +++ b/examples/widgets/widgets/charactermap/characterwidget.py @@ -0,0 +1,133 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from textwrap import dedent + +from PySide6.QtCore import QSize, Qt, Slot, Signal +from PySide6.QtGui import (QBrush, QFont, QFontDatabase, QFontMetrics, + QPainter, QPen) +from PySide6.QtWidgets import QToolTip, QWidget + +COLUMNS = 16 + + +class CharacterWidget(QWidget): + + character_selected = Signal(str) + + def __init__(self, parent=None): + super().__init__(parent) + + self._display_font = QFont() + self._last_key = -1 + self._square_size = int(0) + + self.calculate_square_size() + self.setMouseTracking(True) + + @Slot(QFont) + def update_font(self, font): + self._display_font.setFamily(font.family()) + self.calculate_square_size() + self.adjustSize() + self.update() + + @Slot(str) + def update_size(self, fontSize): + self._display_font.setPointSize(int(fontSize)) + self.calculate_square_size() + self.adjustSize() + self.update() + + @Slot(str) + def update_style(self, fontStyle): + old_strategy = self._display_font.styleStrategy() + self._display_font = QFontDatabase.font(self._display_font.family(), + fontStyle, + self._display_font.pointSize()) + self._display_font.setStyleStrategy(old_strategy) + self.calculate_square_size() + self.adjustSize() + self.update() + + @Slot(bool) + def update_font_merging(self, enable): + if enable: + self._display_font.setStyleStrategy(QFont.PreferDefault) + else: + self._display_font.setStyleStrategy(QFont.NoFontMerging) + self.adjustSize() + self.update() + + def calculate_square_size(self): + h = QFontMetrics(self._display_font, self).height() + self._square_size = max(16, 4 + h) + + def sizeHint(self): + return QSize(COLUMNS * self._square_size, + (65536 / COLUMNS) * self._square_size) + + def _unicode_from_pos(self, point): + row = int(point.y() / self._square_size) + return row * COLUMNS + int(point.x() / self._square_size) + + def mouseMoveEvent(self, event): + widget_position = self.mapFromGlobal(event.globalPosition().toPoint()) + key = self._unicode_from_pos(widget_position) + c = chr(key) + family = self._display_font.family() + text = dedent(f''' + <p>Character: <span style="font-size: 24pt; font-family: {family}"> + {c}</span><p>Value: 0x{key:x} + ''') + QToolTip.showText(event.globalPosition().toPoint(), text, self) + + def mousePressEvent(self, event): + if event.button() == Qt.LeftButton: + self._last_key = self._unicode_from_pos(event.position().toPoint()) + if self._last_key != -1: + c = chr(self._last_key) + self.character_selected.emit(f"{c}") + self.update() + else: + super().mousePressEvent(event) + + def paintEvent(self, event): + with QPainter(self) as painter: + self.render(event, painter) + + def render(self, event, painter): + painter = QPainter(self) + painter.fillRect(event.rect(), QBrush(Qt.white)) + painter.setFont(self._display_font) + redraw_rect = event.rect() + begin_row = int(redraw_rect.top() / self._square_size) + end_row = int(redraw_rect.bottom() / self._square_size) + begin_column = int(redraw_rect.left() / self._square_size) + end_column = int(redraw_rect.right() / self._square_size) + painter.setPen(QPen(Qt.gray)) + for row in range(begin_row, end_row + 1): + for column in range(begin_column, end_column + 1): + x = int(column * self._square_size) + y = int(row * self._square_size) + painter.drawRect(x, y, self._square_size, self._square_size) + + font_metrics = QFontMetrics(self._display_font) + painter.setPen(QPen(Qt.black)) + for row in range(begin_row, end_row + 1): + for column in range(begin_column, end_column + 1): + key = int(row * COLUMNS + column) + painter.setClipRect(column * self._square_size, + row * self._square_size, + self._square_size, self._square_size) + + if key == self._last_key: + painter.fillRect(column * self._square_size + 1, + row * self._square_size + 1, + self._square_size, self._square_size, QBrush(Qt.red)) + + text = chr(key) + painter.drawText(column * self._square_size + (self._square_size / 2) + - font_metrics.horizontalAdvance(text) / 2, + row * self._square_size + 4 + font_metrics.ascent(), + text) diff --git a/examples/widgets/widgets/charactermap/doc/charactermap.rst b/examples/widgets/widgets/charactermap/doc/charactermap.rst new file mode 100644 index 000000000..1a38615c4 --- /dev/null +++ b/examples/widgets/widgets/charactermap/doc/charactermap.rst @@ -0,0 +1,8 @@ +Character Map Example +===================== + +The example displays an array of characters which the user can click on +to enter text in a line edit. The contents of the line edit can then be +copied into the clipboard, and pasted into other applications. The +purpose behind this sort of tool is to allow users to enter characters +that may be unavailable or difficult to locate on their keyboards. diff --git a/examples/widgets/widgets/charactermap/fontinfodialog.py b/examples/widgets/widgets/charactermap/fontinfodialog.py new file mode 100644 index 000000000..aa874884f --- /dev/null +++ b/examples/widgets/widgets/charactermap/fontinfodialog.py @@ -0,0 +1,47 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from PySide6.QtCore import Qt, qVersion, qFuzzyCompare +from PySide6.QtGui import QGuiApplication, QFontDatabase +from PySide6.QtWidgets import (QDialog, QDialogButtonBox, + QPlainTextEdit, QVBoxLayout) + + +def _format_font(font): + family = font.family() + size = font.pointSizeF() + return f"{family}, {size}pt" + + +class FontInfoDialog(QDialog): + + def __init__(self, parent): + super().__init__(parent) + self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) + main_layout = QVBoxLayout(self) + text_edit = QPlainTextEdit(self.text(), self) + text_edit.setReadOnly(True) + text_edit.setFont(QFontDatabase.systemFont(QFontDatabase.FixedFont)) + main_layout.addWidget(text_edit) + button_box = QDialogButtonBox(QDialogButtonBox.Close, self) + button_box.rejected.connect(self.reject) + main_layout.addWidget(button_box) + + def text(self): + default_font = QFontDatabase.systemFont(QFontDatabase.GeneralFont) + fixed_font = QFontDatabase.systemFont(QFontDatabase.FixedFont) + title_font = QFontDatabase.systemFont(QFontDatabase.TitleFont) + smallest_readable_font = QFontDatabase.systemFont(QFontDatabase.SmallestReadableFont) + + v = qVersion() + platform = QGuiApplication.platformName() + dpi = self.logicalDpiX() + dpr = self.devicePixelRatio() + text = f"Qt {v} on {platform}, {dpi}DPI" + if not qFuzzyCompare(dpr, float(1)): + text += f", device pixel ratio: {dpr}" + text += ("\n\nDefault font : " + _format_font(default_font) + + "\nFixed font : " + _format_font(fixed_font) + + "\nTitle font : " + _format_font(title_font) + + "\nSmallest font: " + _format_font(smallest_readable_font)) + return text diff --git a/examples/widgets/widgets/charactermap/main.py b/examples/widgets/widgets/charactermap/main.py new file mode 100644 index 000000000..e84a1d8af --- /dev/null +++ b/examples/widgets/widgets/charactermap/main.py @@ -0,0 +1,17 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +import sys + +from PySide6.QtWidgets import QApplication + +from mainwindow import MainWindow + +"""PySide6 port of the widgets/widgets/ charactermap example from Qt6""" + + +if __name__ == "__main__": + app = QApplication(sys.argv) + window = MainWindow() + window.show() + sys.exit(app.exec()) diff --git a/examples/widgets/widgets/charactermap/mainwindow.py b/examples/widgets/widgets/charactermap/mainwindow.py new file mode 100644 index 000000000..d79285def --- /dev/null +++ b/examples/widgets/widgets/charactermap/mainwindow.py @@ -0,0 +1,167 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from PySide6.QtCore import Qt, QSignalBlocker, Slot +from PySide6.QtGui import QGuiApplication, QClipboard, QFont, QFontDatabase +from PySide6.QtWidgets import (QCheckBox, QComboBox, QFontComboBox, + QHBoxLayout, QLabel, QLineEdit, QMainWindow, + QPushButton, QScrollArea, + QVBoxLayout, QWidget) + +from characterwidget import CharacterWidget +from fontinfodialog import FontInfoDialog + + +class MainWindow(QMainWindow): + + def __init__(self, parent=None): + super().__init__(parent) + + self._character_widget = CharacterWidget() + self._filter_combo = QComboBox() + self._style_combo = QComboBox() + self._size_combo = QComboBox() + self._font_combo = QFontComboBox() + self._line_edit = QLineEdit() + self._scroll_area = QScrollArea() + self._font_merging = QCheckBox() + + file_menu = self.menuBar().addMenu("File") + file_menu.addAction("Quit", self.close) + help_menu = self.menuBar().addMenu("Help") + help_menu.addAction("Show Font Info", self.show_info) + help_menu.addAction("About &Qt", qApp.aboutQt) # noqa: F821 + + central_widget = QWidget() + + self._filter_label = QLabel("Filter:") + self._filter_combo = QComboBox() + self._filter_combo.addItem("All", int(QFontComboBox.AllFonts.value)) + self._filter_combo.addItem("Scalable", int(QFontComboBox.ScalableFonts.value)) + self._filter_combo.addItem("Monospaced", int(QFontComboBox.MonospacedFonts.value)) + self._filter_combo.addItem("Proportional", int(QFontComboBox.ProportionalFonts.value)) + self._filter_combo.setCurrentIndex(0) + self._filter_combo.currentIndexChanged.connect(self.filter_changed) + + self._font_label = QLabel("Font:") + self._font_combo = QFontComboBox() + self._size_label = QLabel("Size:") + self._size_combo = QComboBox() + self._style_label = QLabel("Style:") + self._style_combo = QComboBox() + self._font_merging_label = QLabel("Automatic Font Merging:") + self._font_merging = QCheckBox() + self._font_merging.setChecked(True) + + self._scroll_area = QScrollArea() + self._character_widget = CharacterWidget() + self._scroll_area.setWidget(self._character_widget) + self.find_styles(self._font_combo.currentFont()) + self.find_sizes(self._font_combo.currentFont()) + + self._line_edit = QLineEdit() + self._line_edit.setClearButtonEnabled(True) + self._clipboard_button = QPushButton("To clipboard") + self._font_combo.currentFontChanged.connect(self.find_styles) + self._font_combo.currentFontChanged.connect(self.find_sizes) + self._font_combo.currentFontChanged.connect(self._character_widget.update_font) + self._size_combo.currentTextChanged.connect(self._character_widget.update_size) + self._style_combo.currentTextChanged.connect(self._character_widget.update_style) + self._character_widget.character_selected.connect(self.insert_character) + + self._clipboard_button.clicked.connect(self.update_clipboard) + self._font_merging.toggled.connect(self._character_widget.update_font_merging) + + controls_layout = QHBoxLayout() + controls_layout.addWidget(self._filter_label) + controls_layout.addWidget(self._filter_combo, 1) + controls_layout.addWidget(self._font_label) + controls_layout.addWidget(self._font_combo, 1) + controls_layout.addWidget(self._size_label) + controls_layout.addWidget(self._size_combo, 1) + controls_layout.addWidget(self._style_label) + controls_layout.addWidget(self._style_combo, 1) + controls_layout.addWidget(self._font_merging_label) + controls_layout.addWidget(self._font_merging, 1) + controls_layout.addStretch(1) + + line_layout = QHBoxLayout() + line_layout.addWidget(self._line_edit, 1) + line_layout.addSpacing(12) + line_layout.addWidget(self._clipboard_button) + + central_layout = QVBoxLayout(central_widget) + central_layout.addLayout(controls_layout) + central_layout.addWidget(self._scroll_area, 1) + central_layout.addSpacing(4) + central_layout.addLayout(line_layout) + + self.setCentralWidget(central_widget) + self.setWindowTitle("Character Map") + + @Slot(QFont) + def find_styles(self, font): + current_item = self._style_combo.currentText() + self._style_combo.clear() + styles = QFontDatabase.styles(font.family()) + for style in styles: + self._style_combo.addItem(style) + + style_index = self._style_combo.findText(current_item) + + if style_index == -1: + self._style_combo.setCurrentIndex(0) + else: + self._style_combo.setCurrentIndex(style_index) + + @Slot(int) + def filter_changed(self, f): + filter = QFontComboBox.FontFilter(self._filter_combo.itemData(f)) + self._font_combo.setFontFilters(filter) + count = self._font_combo.count() + self.statusBar().showMessage(f"{count} font(s) found") + + @Slot(QFont) + def find_sizes(self, font): + current_size = self._size_combo.currentText() + with QSignalBlocker(self._size_combo): + # sizeCombo signals are now blocked until end of scope + self._size_combo.clear() + + style = QFontDatabase.styleString(font) + if QFontDatabase.isSmoothlyScalable(font.family(), style): + sizes = QFontDatabase.standardSizes() + for size in sizes: + self._size_combo.addItem(f"{size}") + self._size_combo.setEditable(True) + else: + sizes = QFontDatabase.smoothSizes(font.family(), style) + for size in sizes: + self._size_combo.addItem(f"{size}") + self._size_combo.setEditable(False) + + size_index = self._size_combo.findText(current_size) + + if size_index == -1: + self._size_combo.setCurrentIndex(max(0, self._size_combo.count() / 3)) + else: + self._size_combo.setCurrentIndex(size_index) + + @Slot(str) + def insert_character(self, character): + self._line_edit.insert(character) + + @Slot() + def update_clipboard(self): + clipboard = QGuiApplication.clipboard() + clipboard.setText(self._line_edit.text(), QClipboard.Clipboard) + clipboard.setText(self._line_edit.text(), QClipboard.Selection) + + @Slot() + def show_info(self): + screen_geometry = self.screen().geometry() + dialog = FontInfoDialog(self) + dialog.setWindowTitle("Fonts") + dialog.setAttribute(Qt.WA_DeleteOnClose) + dialog.resize(screen_geometry.width() / 4, screen_geometry.height() / 4) + dialog.show() diff --git a/examples/widgets/widgets/digitalclock/digitalclock.py b/examples/widgets/widgets/digitalclock/digitalclock.py new file mode 100644 index 000000000..f0030b356 --- /dev/null +++ b/examples/widgets/widgets/digitalclock/digitalclock.py @@ -0,0 +1,41 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +import sys + +from PySide6.QtCore import QTime, QTimer, Slot +from PySide6.QtWidgets import QApplication, QLCDNumber + + +class DigitalClock(QLCDNumber): + def __init__(self, parent=None): + super().__init__(parent) + self.setSegmentStyle(QLCDNumber.Filled) + self.setDigitCount(8) + + self.timer = QTimer(self) + self.timer.timeout.connect(self.show_time) + self.timer.start(1000) + + self.show_time() + + self.setWindowTitle("Digital Clock") + self.resize(250, 60) + + @Slot() + def show_time(self): + time = QTime.currentTime() + text = time.toString("hh:mm:ss") + + # Blinking effect + if (time.second() % 2) == 0: + text = text.replace(":", " ") + + self.display(text) + + +if __name__ == "__main__": + + app = QApplication(sys.argv) + clock = DigitalClock() + clock.show() + sys.exit(app.exec()) diff --git a/examples/widgets/widgets/digitalclock/digitalclock.pyproject b/examples/widgets/widgets/digitalclock/digitalclock.pyproject new file mode 100644 index 000000000..03c3b6bb7 --- /dev/null +++ b/examples/widgets/widgets/digitalclock/digitalclock.pyproject @@ -0,0 +1,3 @@ +{ + "files": ["digitalclock.py"] +} diff --git a/examples/widgets/widgets/digitalclock/doc/digitalclock-screenshot.png b/examples/widgets/widgets/digitalclock/doc/digitalclock-screenshot.png Binary files differnew file mode 100644 index 000000000..2234d7665 --- /dev/null +++ b/examples/widgets/widgets/digitalclock/doc/digitalclock-screenshot.png diff --git a/examples/widgets/widgets/digitalclock/doc/digitalclock.rst b/examples/widgets/widgets/digitalclock/doc/digitalclock.rst new file mode 100644 index 000000000..d13275d24 --- /dev/null +++ b/examples/widgets/widgets/digitalclock/doc/digitalclock.rst @@ -0,0 +1,14 @@ +Digital Clock Example +===================== + +.. tags:: Android + +The Digital Clock example shows how to use QLCDNumber to display a number with +LCD-like digits. + +.. image:: digitalclock-screenshot.png + :width: 400 + :alt: Digital Clock Screenshot + +This example also demonstrates how QTimer can be used to update a widget at +regular intervals. diff --git a/examples/widgets/widgets/tetrix/doc/tetrix-screenshot.png b/examples/widgets/widgets/tetrix/doc/tetrix-screenshot.png Binary files differnew file mode 100644 index 000000000..2c3dade39 --- /dev/null +++ b/examples/widgets/widgets/tetrix/doc/tetrix-screenshot.png diff --git a/examples/widgets/widgets/tetrix/doc/tetrix.rst b/examples/widgets/widgets/tetrix/doc/tetrix.rst new file mode 100644 index 000000000..0749de9de --- /dev/null +++ b/examples/widgets/widgets/tetrix/doc/tetrix.rst @@ -0,0 +1,38 @@ +Tetrix +====== + +The Tetrix example is a Qt version of the classic Tetrix game. + +.. image:: tetrix-screenshot.png + :width: 400 + :alt: Tetrix main window + +The object of the game is to stack pieces dropped from the top of the playing +area so that they fill entire rows at the bottom of the playing area. + +When a row is filled, all the blocks on that row are removed, the player earns +a number of points, and the pieces above are moved down to occupy that row. If +more than one row is filled, the blocks on each row are removed, and the player +earns extra points. + +The **Left** cursor key moves the current piece one space to the left, the +**Right** cursor key moves it one space to the right, the **Up** cursor key +rotates the piece counter-clockwise by 90 degrees, and the **Down** cursor key +rotates the piece clockwise by 90 degrees. + +To avoid waiting for a piece to fall to the bottom of the board, press **D** to +immediately move the piece down by one row, or press the **Space** key to drop +it as close to the bottom of the board as possible. + +This example shows how a simple game can be created using only three classes: + +* The ``TetrixWindow`` class is used to display the player's score, number of + lives, and information about the next piece to appear. +* The ``TetrixBoard`` class contains the game logic, handles keyboard input, and + displays the pieces on the playing area. +* The ``TetrixPiece`` class contains information about each piece. + +In this approach, the ``TetrixBoard`` class is the most complex class, since it +handles the game logic and rendering. One benefit of this is that the +``TetrixWindow`` and ``TetrixPiece`` classes are very simple and contain only a +minimum of code. diff --git a/examples/widgets/widgets/tetrix/tetrix.py b/examples/widgets/widgets/tetrix/tetrix.py new file mode 100644 index 000000000..b5df2aa35 --- /dev/null +++ b/examples/widgets/widgets/tetrix/tetrix.py @@ -0,0 +1,472 @@ +# Copyright (C) 2013 Riverbank Computing Limited. +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +"""PySide6 port of the widgets/widgets/tetrix example from Qt v5.x""" + +from enum import IntEnum +import random +import sys + +from PySide6.QtCore import QBasicTimer, QSize, Qt, Signal, Slot +from PySide6.QtGui import QColor, QPainter, QPixmap +from PySide6.QtWidgets import (QApplication, QFrame, QGridLayout, QLabel, + QLCDNumber, QPushButton, QWidget) + + +class Piece(IntEnum): + NoShape = 0 + ZShape = 1 + SShape = 2 + LineShape = 3 + TShape = 4 + SquareShape = 5 + LShape = 6 + MirroredLShape = 7 + + +class TetrixWindow(QWidget): + def __init__(self): + super().__init__() + + self.board = TetrixBoard() + + next_piece_label = QLabel() + next_piece_label.setFrameStyle(QFrame.Box | QFrame.Raised) + next_piece_label.setAlignment(Qt.AlignCenter) + self.board.set_next_piece_label(next_piece_label) + + score_lcd = QLCDNumber(5) + score_lcd.setSegmentStyle(QLCDNumber.Filled) + level_lcd = QLCDNumber(2) + level_lcd.setSegmentStyle(QLCDNumber.Filled) + lines_lcd = QLCDNumber(5) + lines_lcd.setSegmentStyle(QLCDNumber.Filled) + + start_button = QPushButton("&Start") + start_button.setFocusPolicy(Qt.NoFocus) + quit_button = QPushButton("&Quit") + quit_button.setFocusPolicy(Qt.NoFocus) + pause_button = QPushButton("&Pause") + pause_button.setFocusPolicy(Qt.NoFocus) + + start_button.clicked.connect(self.board.start) + pause_button.clicked.connect(self.board.pause) + quit_button.clicked.connect(qApp.quit) # noqa: F821 + self.board.score_changed.connect(score_lcd.display) + self.board.level_changed.connect(level_lcd.display) + self.board.lines_removed_changed.connect(lines_lcd.display) + + layout = QGridLayout(self) + layout.addWidget(self.create_label("NEXT"), 0, 0) + layout.addWidget(next_piece_label, 1, 0) + layout.addWidget(self.create_label("LEVEL"), 2, 0) + layout.addWidget(level_lcd, 3, 0) + layout.addWidget(start_button, 4, 0) + layout.addWidget(self.board, 0, 1, 6, 1) + layout.addWidget(self.create_label("SCORE"), 0, 2) + layout.addWidget(score_lcd, 1, 2) + layout.addWidget(self.create_label("LINES REMOVED"), 2, 2) + layout.addWidget(lines_lcd, 3, 2) + layout.addWidget(quit_button, 4, 2) + layout.addWidget(pause_button, 5, 2) + + self.setWindowTitle("Tetrix") + self.resize(550, 370) + + def create_label(self, text): + lbl = QLabel(text) + lbl.setAlignment(Qt.AlignHCenter | Qt.AlignBottom) + return lbl + + +class TetrixBoard(QFrame): + board_width = 10 + board_height = 22 + + score_changed = Signal(int) + + level_changed = Signal(int) + + lines_removed_changed = Signal(int) + + def __init__(self, parent=None): + super().__init__(parent) + + self.timer = QBasicTimer() + self.nextPieceLabel = None + self._is_waiting_after_line = False + self._cur_piece = TetrixPiece() + self._next_piece = TetrixPiece() + self._cur_x = 0 + self._cur_y = 0 + self._num_lines_removed = 0 + self._num_pieces_dropped = 0 + self.score = 0 + self.level = 0 + self.board = None + + self.setFrameStyle(QFrame.Panel | QFrame.Sunken) + self.setFocusPolicy(Qt.StrongFocus) + self._is_started = False + self._is_paused = False + self.clear_board() + + self._next_piece.set_random_shape() + + def shape_at(self, x, y): + return self.board[(y * TetrixBoard.board_width) + x] + + def set_shape_at(self, x, y, shape): + self.board[(y * TetrixBoard.board_width) + x] = shape + + def timeout_time(self): + return 1000 / (1 + self.level) + + def square_width(self): + return self.contentsRect().width() / TetrixBoard.board_width + + def square_height(self): + return self.contentsRect().height() / TetrixBoard.board_height + + def set_next_piece_label(self, label): + self.nextPieceLabel = label + + def sizeHint(self): + return QSize(TetrixBoard.board_width * 15 + self.frameWidth() * 2, + TetrixBoard.board_height * 15 + self.frameWidth() * 2) + + def minimum_size_hint(self): + return QSize(TetrixBoard.board_width * 5 + self.frameWidth() * 2, + TetrixBoard.board_height * 5 + self.frameWidth() * 2) + + @Slot() + def start(self): + if self._is_paused: + return + + self._is_started = True + self._is_waiting_after_line = False + self._num_lines_removed = 0 + self._num_pieces_dropped = 0 + self.score = 0 + self.level = 1 + self.clear_board() + + self.lines_removed_changed.emit(self._num_lines_removed) + self.score_changed.emit(self.score) + self.level_changed.emit(self.level) + + self.new_piece() + self.timer.start(self.timeout_time(), self) + + @Slot() + def pause(self): + if not self._is_started: + return + + self._is_paused = not self._is_paused + if self._is_paused: + self.timer.stop() + else: + self.timer.start(self.timeout_time(), self) + + self.update() + + def paintEvent(self, event): + super(TetrixBoard, self).paintEvent(event) + + with QPainter(self) as painter: + rect = self.contentsRect() + + if self._is_paused: + painter.drawText(rect, Qt.AlignCenter, "Pause") + return + + board_top = rect.bottom() - TetrixBoard.board_height * self.square_height() + + for i in range(TetrixBoard.board_height): + for j in range(TetrixBoard.board_width): + shape = self.shape_at(j, TetrixBoard.board_height - i - 1) + if shape != Piece.NoShape: + self.draw_square(painter, + rect.left() + j * self.square_width(), + board_top + i * self.square_height(), shape) + + if self._cur_piece.shape() != Piece.NoShape: + for i in range(4): + x = self._cur_x + self._cur_piece.x(i) + y = self._cur_y - self._cur_piece.y(i) + self.draw_square(painter, rect.left() + x * self.square_width(), + board_top + + (TetrixBoard.board_height - y - 1) * self.square_height(), + self._cur_piece.shape()) + + def keyPressEvent(self, event): + if not self._is_started or self._is_paused or self._cur_piece.shape() == Piece.NoShape: + super(TetrixBoard, self).keyPressEvent(event) + return + + key = event.key() + if key == Qt.Key_Left: + self.try_move(self._cur_piece, self._cur_x - 1, self._cur_y) + elif key == Qt.Key_Right: + self.try_move(self._cur_piece, self._cur_x + 1, self._cur_y) + elif key == Qt.Key_Down: + self.try_move(self._cur_piece.rotated_right(), self._cur_x, self._cur_y) + elif key == Qt.Key_Up: + self.try_move(self._cur_piece.rotated_left(), self._cur_x, self._cur_y) + elif key == Qt.Key_Space: + self.drop_down() + elif key == Qt.Key_D: + self.one_line_down() + else: + super(TetrixBoard, self).keyPressEvent(event) + + def timerEvent(self, event): + if event.timerId() == self.timer.timerId(): + if self._is_waiting_after_line: + self._is_waiting_after_line = False + self.new_piece() + self.timer.start(self.timeout_time(), self) + else: + self.one_line_down() + else: + super(TetrixBoard, self).timerEvent(event) + + def clear_board(self): + self.board = [ + Piece.NoShape for _ in range(TetrixBoard.board_height * TetrixBoard.board_width)] + + def drop_down(self): + drop_height = 0 + new_y = self._cur_y + while new_y > 0: + if not self.try_move(self._cur_piece, self._cur_x, new_y - 1): + break + new_y -= 1 + drop_height += 1 + + self.piece_dropped(drop_height) + + def one_line_down(self): + if not self.try_move(self._cur_piece, self._cur_x, self._cur_y - 1): + self.piece_dropped(0) + + def piece_dropped(self, dropHeight): + for i in range(4): + x = self._cur_x + self._cur_piece.x(i) + y = self._cur_y - self._cur_piece.y(i) + self.set_shape_at(x, y, self._cur_piece.shape()) + + self._num_pieces_dropped += 1 + if self._num_pieces_dropped % 25 == 0: + self.level += 1 + self.timer.start(self.timeout_time(), self) + self.level_changed.emit(self.level) + + self.score += dropHeight + 7 + self.score_changed.emit(self.score) + self.remove_full_lines() + + if not self._is_waiting_after_line: + self.new_piece() + + def remove_full_lines(self): + num_full_lines = 0 + + for i in range(TetrixBoard.board_height - 1, -1, -1): + line_is_full = True + + for j in range(TetrixBoard.board_width): + if self.shape_at(j, i) == Piece.NoShape: + line_is_full = False + break + + if line_is_full: + num_full_lines += 1 + for k in range(i, TetrixBoard.board_height - 1): + for j in range(TetrixBoard.board_width): + self.set_shape_at(j, k, self.shape_at(j, k + 1)) + + for j in range(TetrixBoard.board_width): + self.set_shape_at(j, TetrixBoard.board_height - 1, Piece.NoShape) + + if num_full_lines > 0: + self._num_lines_removed += num_full_lines + self.score += 10 * num_full_lines + self.lines_removed_changed.emit(self._num_lines_removed) + self.score_changed.emit(self.score) + + self.timer.start(500, self) + self._is_waiting_after_line = True + self._cur_piece.set_shape(Piece.NoShape) + self.update() + + def new_piece(self): + self._cur_piece = self._next_piece + self._next_piece.set_random_shape() + self.show_next_piece() + self._cur_x = TetrixBoard.board_width // 2 + 1 + self._cur_y = TetrixBoard.board_height - 1 + self._cur_piece.min_y() + + if not self.try_move(self._cur_piece, self._cur_x, self._cur_y): + self._cur_piece.set_shape(Piece.NoShape) + self.timer.stop() + self._is_started = False + + def show_next_piece(self): + if self.nextPieceLabel is not None: + return + + dx = self._next_piece.max_x() - self._next_piece.min_x() + 1 + dy = self._next_piece.max_y() - self._next_piece.min_y() + 1 + + pixmap = QPixmap(dx * self.square_width(), dy * self.square_height()) + with QPainter(pixmap) as painter: + painter.fillRect(pixmap.rect(), self.nextPieceLabel.palette().background()) + + for i in range(4): + x = self._next_piece.x(i) - self._next_piece.min_x() + y = self._next_piece.y(i) - self._next_piece.min_y() + self.draw_square(painter, x * self.square_width(), + y * self.square_height(), self._next_piece.shape()) + + self.nextPieceLabel.setPixmap(pixmap) + + def try_move(self, newPiece, newX, newY): + for i in range(4): + x = newX + newPiece.x(i) + y = newY - newPiece.y(i) + if x < 0 or x >= TetrixBoard.board_width or y < 0 or y >= TetrixBoard.board_height: + return False + if self.shape_at(x, y) != Piece.NoShape: + return False + + self._cur_piece = newPiece + self._cur_x = newX + self._cur_y = newY + self.update() + return True + + def draw_square(self, painter, x, y, shape): + color_table = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC, + 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00] + + color = QColor(color_table[shape]) + painter.fillRect(x + 1, y + 1, self.square_width() - 2, self.square_height() - 2, color) + + painter.setPen(color.lighter()) + painter.drawLine(x, y + self.square_height() - 1, x, y) + painter.drawLine(x, y, x + self.square_width() - 1, y) + + painter.setPen(color.darker()) + painter.drawLine(x + 1, y + self.square_height() - 1, + x + self.square_width() - 1, y + self.square_height() - 1) + painter.drawLine(x + self.square_width() - 1, + y + self.square_height() - 1, x + self.square_width() - 1, y + 1) + + +class TetrixPiece(object): + coords_table = ( + ((0, 0), (0, 0), (0, 0), (0, 0)), + ((0, -1), (0, 0), (-1, 0), (-1, 1)), + ((0, -1), (0, 0), (1, 0), (1, 1)), + ((0, -1), (0, 0), (0, 1), (0, 2)), + ((-1, 0), (0, 0), (1, 0), (0, 1)), + ((0, 0), (1, 0), (0, 1), (1, 1)), + ((-1, -1), (0, -1), (0, 0), (0, 1)), + ((1, -1), (0, -1), (0, 0), (0, 1)) + ) + + def __init__(self): + self.coords = [[0, 0] for _ in range(4)] + self._piece_shape = Piece.NoShape + + self.set_shape(Piece.NoShape) + + def shape(self): + return self._piece_shape + + def set_shape(self, shape): + table = TetrixPiece.coords_table[shape] + for i in range(4): + for j in range(2): + self.coords[i][j] = table[i][j] + + self._piece_shape = shape + + def set_random_shape(self): + self.set_shape(random.randint(1, 7)) + + def x(self, index): + return self.coords[index][0] + + def y(self, index): + return self.coords[index][1] + + def set_x(self, index, x): + self.coords[index][0] = x + + def set_y(self, index, y): + self.coords[index][1] = y + + def min_x(self): + m = self.coords[0][0] + for i in range(4): + m = min(m, self.coords[i][0]) + + return m + + def max_x(self): + m = self.coords[0][0] + for i in range(4): + m = max(m, self.coords[i][0]) + + return m + + def min_y(self): + m = self.coords[0][1] + for i in range(4): + m = min(m, self.coords[i][1]) + + return m + + def max_y(self): + m = self.coords[0][1] + for i in range(4): + m = max(m, self.coords[i][1]) + + return m + + def rotated_left(self): + if self._piece_shape == Piece.SquareShape: + return self + + result = TetrixPiece() + result._piece_shape = self._piece_shape + for i in range(4): + result.set_x(i, self.y(i)) + result.set_y(i, -self.x(i)) + + return result + + def rotated_right(self): + if self._piece_shape == Piece.SquareShape: + return self + + result = TetrixPiece() + result._piece_shape = self._piece_shape + for i in range(4): + result.set_x(i, -self.y(i)) + result.set_y(i, self.x(i)) + + return result + + +if __name__ == '__main__': + app = QApplication(sys.argv) + window = TetrixWindow() + window.show() + random.seed(None) + sys.exit(app.exec()) diff --git a/examples/widgets/widgets/tetrix/tetrix.pyproject b/examples/widgets/widgets/tetrix/tetrix.pyproject new file mode 100644 index 000000000..75121ea64 --- /dev/null +++ b/examples/widgets/widgets/tetrix/tetrix.pyproject @@ -0,0 +1,3 @@ +{ + "files": ["tetrix.py"] +} |