07 QString saveState() const;
08 QSize sizeHint() const;
09 protected:
10 void paintEvent(QPaintEvent *event);
11 void mousePressEvent(QMouseEvent *event);
12 private:
13 enum { Empty = '-', Cross = 'X', Nought = '0' };
14 void clearBoard();
15 void restoreState();
16 QString sessionFileName() const;
17 QRect cellRect(int row, int column) const;
18 int cellWidth() const { return width() / 3; }
19 int cellHeight() const { return height() / 3; }
20 bool threeInARow(int row1, int col1, int row3, int col3) const;
21 char board[3][3];
22 int turnNumber;
23 };
Класс
01 TicTacToe::TicTacToe(QWidget *parent, const char *name)
02 : QWidget(parent, name)
03 {
04 clearBoard();
05 if (qApp->isSessionRestored())
06 restoreState();
07 setWindowTitle(tr("Tic-Tac-Toe"));
08 }
В конструкторе мы стираем игровое поле и, если приложение было вызвано с опцией
01 void TicTacToe::clearBoard()
02 {
03 for (int row= 0; row < 3; ++row) {
04 for (int column = 0; column < 3; ++column) {
05 board[row][column] = Empty;
06 }
07 }
08 turnNumber = 0;
09 }
В функции
01 QString TicTacToe::saveState() const
02 {
03 QFile file(sessionFileName());
04 if (file.open(QIODevice::WriteOnly)) {
05 QTextStream out(&file);
06 for (int row = 0; row < 3; ++row) {
07 for (int column = 0; column < 3; ++column) {
08 out << board[row][column];
09 }
10 }
11 }
12 return file.fileName();
13 }
В функции
01 QString TicTacToe::sessionFileName() const
02 {
03 return QDir::homePath() + "/.tictactoe_"
04 + qApp->sessionId() + "_" + qApp->sessionKey();
05 }
Закрытая функция
01 void TicTacToe::restoreState()
02 {
03 QFile file(sessionFileName());
04 if (file.open(QIODevice::ReadOnly)) {
05 QTextStream in(&file);
06 for (int row = 0; row < 3; ++row) {
07 for (int column = 0; column < 3; ++column) {
08 in >> board[row][column];
09 if (board[row][column] != Empty)