I make tic tac toe on qt, I can not figure out how to make the tic and tac toe put in turns, help, please
Closed due to the fact that the issue is too general for the participants of sercxjo , pavel , Dmitriy Simushev , dirkgntly , Nicolas Chabanovsky ♦ 15 Sep '16 at 6:37 .
Please correct the question so that it describes the specific problem with sufficient detail to determine the appropriate answer. Do not ask a few questions at once. See “How to ask a good question?” For clarification. If the question can be reformulated according to the rules set out in the certificate , edit it .
- hint - you need an additional variable where the current element will be written - a cross or a toe. But in fact, you can use the fact that the move number just shows what needs to be displayed. - KoVadim
1 answer
The most beautiful, in my opinion, the decision will use the state machine . For example, the button:
#ifndef TEST_H #define TEST_H #include <QPushButton> #include <QStateMachine> #include <QSignalTransition> #include <QAbstractState> #include <QDebug> class State : public QState{ Q_OBJECT QString _name; public: explicit State(const QString &name): _name(name) {} signals: void entered(const QString &name); protected: void onEntry(QEvent *event){ emit entered(_name); QState::onEntry(event); } }; class Test : public QPushButton{ Q_OBJECT QStateMachine _machine; public: Test(QWidget *parent = 0): QPushButton(parent) { State *x = new State("x"); connect(x, SIGNAL(entered(QString)), this, SLOT(_setText(QString))); _machine.addState(x); State *o = new State("o"); connect(o, SIGNAL(entered(QString)), this, SLOT(_setText(QString))); _machine.addState(o); x->addTransition(this, SIGNAL(clicked(bool)), o); o->addTransition(this, SIGNAL(clicked(bool)), x); _machine.setInitialState(x); _machine.start(); } private slots: void _setText(const QString &text){ setText(text); } }; #endif // TEST_H If you click on it, the transition from state x to state o will occur, and the text on the button will change.
If you do not want to bother with the machine states, the same effect can be achieved in another way:
#ifndef TEST_H #define TEST_H #include <QPushButton> #include <QVector> class Strings{ int _i; QVector<QString> _strings; public: Strings(): _i(0) { _strings.append("x"); _strings.append("o"); } const QString& next(){ return _strings[_nextIndex()]; } private: int _nextIndex(){ return _i++ % _strings.size(); } }; class Test : public QPushButton{ Q_OBJECT Strings _strings; public: Test(QWidget *parent = 0): QPushButton(parent) { connect(this, SIGNAL(clicked(bool)), this, SLOT(_setNextText())); _setNextText(); } private slots: void _setNextText(){ setText(_strings.next()); } }; #endif // TEST_H It is simpler, but not so beautiful, and you cannot tell your friends that the state machine is used in your noughts and crosses.