tictactoe with pyqt5

Solutions on MaxInterview for tictactoe with pyqt5 by the best coders in the world

showing results for - "tictactoe with pyqt5"
Zuriel
16 Jun 2016
1import sys
2from PyQt5.QtCore import QPointF, QRectF, Qt
3from PyQt5.QtGui import QPainter, QPen
4from PyQt5.QtWidgets import (QApplication, QGraphicsItem, QGraphicsScene,
5                             QGraphicsView)
6
7class TicTacToe(QGraphicsItem):
8    # http://pyqt.sourceforge.net/Docs/PyQt5/api/QtWidgets/qgraphicsitem.html
9
10    def __init__(self):
11        super(TicTacToe, self).__init__()
12        self.board = [[None, None, None],[None, None, None], [None, None, None]]
13        self.O = 0
14        self.X = 1
15        self.turn = self.O
16
17    def boundingRect(self):
18        # http://doc.qt.io/qt-5/qgraphicsitem.html#boundingRect
19        return QRectF(0,0,300,300)
20
21    def select(self, x, y):
22        if x < 0 or y < 0 or x >= 3 or y >= 3:
23            return
24        if self.board[y][x] == None:
25            self.board[y][x] = self.turn
26            self.turn = 1 - self.turn
27
28    def paint(self, painter, option, widget):
29        # http://doc.qt.io/qt-5/qgraphicsitem.html#paint
30        painter.setPen(Qt.black)
31        painter.drawLine(0,100,300,100)
32        painter.drawLine(0,200,300,200)
33        painter.drawLine(100,0,100,300)
34        painter.drawLine(200,0,200,300)
35        for y in range(3):
36            for x in range(3):
37                if self.board[y][x] == self.O:
38                    painter.setPen(QPen(Qt.red, 3))
39                    painter.drawEllipse(QPointF(50+x*100, 50+y*100), 35, 35)
40                elif self.board[y][x] == self.X:
41                    painter.setPen(QPen(Qt.blue, 3))
42                    painter.drawLine(20+x*100, 20+y*100, 80+x*100, 80+y*100)
43                    painter.drawLine(20+x*100, 80+y*100, 80+x*100, 20+y*100)
44
45    def mousePressEvent(self, event):
46        # http://doc.qt.io/qt-5/qgraphicsitem.html#mousePressEvent
47        self.select(int(event.pos().x()/100), int(event.pos().y()/100))
48        self.update()
49
50class MainWindow(QGraphicsView):
51    # http://pyqt.sourceforge.net/Docs/PyQt5/api/QtWidgets/qgraphicsview.html
52    def __init__(self):
53        super(MainWindow, self).__init__()
54        scene = QGraphicsScene(self)
55        self.tictactoe = TicTacToe()
56        scene.addItem(self.tictactoe)
57        scene.setSceneRect(0, 0, 300, 300)
58        self.setScene(scene)
59        self.show()
60
queries leading to this page
tictactoe pyqt5tictactoe with pyqt5