Untitled
2 weeks ago in Plain Text
import sys
from PyQt5.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QRadioButton
)
class TicTacToe(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Крестики-нолики")
# Основной макет
self.layout = QVBoxLayout()
# Виджеты управления
self.control_layout = QHBoxLayout()
self.x_radio = QRadioButton("Игрок X")
self.o_radio = QRadioButton("Игрок O")
self.x_radio.setChecked(True)
self.x_radio.toggled.connect(self.start_new_game)
self.o_radio.toggled.connect(self.start_new_game)
self.new_game_button = QPushButton("Новая игра")
self.new_game_button.clicked.connect(self.start_new_game)
self.control_layout.addWidget(self.x_radio)
self.control_layout.addWidget(self.o_radio)
self.control_layout.addWidget(self.new_game_button)
# Поле для результата
self.result = QLabel("Ходит X")
self.layout.addWidget(self.result)
# Игровое поле
self.button_grid = [[QPushButton("") for _ in range(3)] for _ in range(3)]
self.grid_layout = QVBoxLayout()
for row in self.button_grid:
row_layout = QHBoxLayout()
for button in row:
button.setFixedSize(100, 100)
button.clicked.connect(self.handle_button_click)
row_layout.addWidget(button)
self.grid_layout.addLayout(row_layout)
self.layout.addLayout(self.grid_layout)
# Добавляем элементы на окно
self.layout.addLayout(self.control_layout)
self.setLayout(self.layout)
self.current_player = "X"
self.game_active = True
def handle_button_click(self):
if not self.game_active:
return
button = self.sender()
if button.text() == "":
button.setText(self.current_player)
if self.check_winner():
self.result.setText(f"Выиграл {self.current_player}!")
self.game_active = False
elif self.check_draw():
self.result.setText("Ничья!")
self.game_active = False
else:
self.current_player = "O" if self.current_player == "X" else "X"
self.result.setText(f"Ходит {self.current_player}")
def check_winner(self):
# Проверяем строки, столбцы и диагонали
for row in self.button_grid:
if row[0].text() == row[1].text() == row[2].text() != "":
return True
for col in range(3):
if (self.button_grid[0][col].text() == self.button_grid[1][col].text() == self.button_grid[2][col].text() != ""):
return True
if (self.button_grid[0][0].text() == self.button_grid[1][1].text() == self.button_grid[2][2].text() != "") or \
(self.button_grid[0][2].text() == self.button_grid[1][1].text() == self.button_grid[2][0].text() != ""):
return True
return False
def check_draw(self):
return all(button.text() != "" for row in self.button_grid for button in row)
def start_new_game(self):
self.current_player = "X" if self.x_radio.isChecked() else "O"
self.result.setText(f"Ходит {self.current_player}")
self.game_active = True
for row in self.button_grid:
for button in row:
button.setText("")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = TicTacToe()
window.show()
sys.exit(app.exec_())