Qt Quick implements the crazy arithmetic game

Source: Internet
Author: User

Use Qt Quick to write a little game: crazy arithmetic. Support for Windows and Android two platforms.

this is your ticket. Pro: Blog Star selection, click Vote I vote, thank you . If you have voted, you can also point oh, every day can cast a vote.

The game is simple but involves following your Qt Quick theme:

    • Implement a Button yourself
    • Adaptive resolution
    • Internationalization
    • QML and C + + mixed programming
    • APK icon Settings
    • APK name of Chinese
    • Animation

In fact, all of this is covered in my book, "Qt quick Core programming ," where interested friends can read my book.

Let's take a look at the effect first.

Android Phone Running effect

Here is a list of Android apps:



See "Crazy arithmetic" that application, the icon is my own painting, the name is Chinese.

Then look at the effect of the game in progress:



The middle of the interface, the first line is a countdown, a few seconds. The second line is the arithmetic problem. The third line is two buttons, choose right and wrong, judge the correct words, continue to the next question, if the election is wrong, the game is over, you can see the figure below.



At the end of the game show the current correct number of questions, history of the best results. Below the interface is a two button, click "Again" can replay, click "Exit" to end the entire game. The end of the game interface, using the Spring Animation (sprintganimation), has some animated effects.

SOURCE Analysis

We take a quick look at the source code and take the important part.

Internationalization

In this simple example, only the QML document has a string that needs to be translated. There are some changes in the Pro file:

Translations = madmath_zh_cn.tslupdate_only {    SOURCES = main.qml}

Using the Qt command-line development environment, switch to the project directory, execute lupdate madmath.pro can generate TS file, then use linguist translation, publish, and then add the QM file to QRC, finally in Main.cpp according to the user language environment load QM File.

The main.cpp code is as follows:

#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QFont> #include < qqmlcontext> #include <QIcon> #include <QLocale> #include <QTranslator> #include "sizeUtil.h" #    Include "problem.h" int main (int argc, char *argv[]) {qguiapplication app (argc, argv);    Qfont f = app.font ();    F.setpointsize (24);    App.setwindowicon (Qicon (":/res/madmath_36.png"));    Qlocale locale = Qlocale::system ();        if (locale.language () = = Qlocale::chinese) {qtranslator *translator = new Qtranslator (&app);        if (Translator->load (":/MADMATH_ZH_CN.QM")) {App.installtranslator (translator);    }} Qqmlapplicationengine engine;    Engine.rootcontext ()->setcontextproperty ("Sizeutil", new Sizeutil);    Engine.rootcontext ()->setcontextproperty ("Problems", new Mathproblem);    Engine.load (Qurl (qstringliteral ("qrc:///main.qml")); return app.exec ();}

ImageButton

Implements a simple Picture button--imagebutton, within the imagebutton.qml file. All source code:

Import QtQuick 2.0Rectangle {    id:btn;    Property alias NormalImage:normal.source;    Property alias PressedImage:pressed.source;    Signal clicked ();    Image {        id:normal;        anchors.fill:parent;    }    Image {        id:pressed;        anchors.fill:parent;        Visible:false;    }    implicitwidth:64;    implicitheight:48;    Mousearea {        anchors.fill:parent;        onpressed: {            pressed.visible = true;            Normal.visible = false;        }        onreleased: {            pressed.visible = false;            Normal.visible = true;            Btn.clicked ();}}}    

The ImageButton has two states: normal and pressed. Both states each have a picture. Two images were toggled in the mouse event.

A clicked () signal is also defined. The properties aliases Normalimage and Pressedimage are exposed to the desired picture for setting the button.

ImageButton is also very simple to use, here is the example used in MAIN.QML:

    ImageButton {        id:wrong;        Anchors.right:parent.horizontalCenter;        Anchors.rightmargin:12;        Anchors.top:problem.bottom;        anchors.topmargin:20;        NORMALIMAGE:QT.RESOLVEDURL ("Res/wrong_normal.png");        PRESSEDIMAGE:QT.RESOLVEDURL ("Res/wrong_selected.png");        Width:root.dpiFactor *;        Height:root.dpiFactor *;        OnClicked:root.check (FALSE);    }

QML and C + + mixed programming

Arithmetic goal generation and result judgement, I put in C + +, in the Mathproblem implementation. There is also some DPI information, also in C + +, implemented in Sizeutil.

For details on QML and C + + mixed programming, see my Blog or my book, "Qt Quick Core Programming ", which is no longer detailed here. We only look at how the topic is out, part of the source code:

QString Mathproblem::next () {    ++m_index;    if (M_index = sizeof (g_answers)/sizeof (G_answers[0]))    {        m_index = 0;    }    int var = qrand ()% 2;    if (Var && (Qrand ()% 2)) var =-var;    M_currentanswer = G_answers[m_index] + qrand ()% 2;    M_currentright = (G_answers[m_index] = = m_currentanswer);    Return QString ("%1%2"). Arg (G_problems[m_index]). Arg (m_currentanswer); BOOL Mathproblem::test (bool right) {    return right = = M_currentright;}

Next () method generates an arithmetic problem. Mathproblem maintains an index that points to the global problem array and the answer array. Next () increments M_index, the answer is confused with a random number, and then determines whether the result of the confusion is consistent with the correct answer. The results of the topic remain in the Boolean variable m_currentright.

Test () tests whether the user's choice is consistent with the actual result.

topic in global array g_problems, the answer is in the global array g_answers.

Animation

When the user answers the wrong question, a prompt interface pops up from the top of the app. I used the springanimation to add some animations to this interface.

The code for Gameoverui is as follows:

    Rectangle {Id:gameoverui;        Border.width:2;        Border.color: "White";        Color: "Lightsteelblue";        Width:root.width * 0.75;        Height:root.height * 0.75;        X:root.width * 0.125;        Y:-height-1;        Visible:false;            Text {id:overtitle;            Anchors.top:parent.top;            Anchors.topMargin:sizeUtil.defaultFontHeight ();            Anchors.horizontalCenter:parent.horizontalCenter;            font.pointsize:30;            Text:qstr ("Game over");        Color: "Red";            } Text {anchors.bottom:parent.verticalCenter;            Anchors.bottommargin:10;            Anchors.right:parent.horizontalCenter;            Anchors.rightmargin:8;            Text:qstr ("New:");            HorizontalAlignment:Text.AlignRight;        Color: "BLACK";            } Text {id:current;            Anchors.bottom:parent.verticalCenter;       Anchors.bottommargin:10;     Anchors.left:parent.horizontalCenter;            Anchors.leftmargin:8;            HorizontalAlignment:Text.AlignLeft;            Color: "Blue";        Font.bold:true;            } Text {anchors.top:current.bottom;            anchors.topmargin:20;            Anchors.right:parent.horizontalCenter;            Anchors.rightmargin:8;            Text:qstr ("best:");            HorizontalAlignment:Text.AlignRight;        Color: "BLACK";            } Text {id:best;            Anchors.top:current.bottom;            anchors.topmargin:20;            Anchors.left:parent.horizontalCenter;            Anchors.leftmargin:8;            HorizontalAlignment:Text.AlignLeft;            Color: "Blue";        Font.bold:true;            } Button {anchors.bottom:parent.bottom;            anchors.bottommargin:40;            Anchors.right:parent.horizontalCenter;            anchors.rightmargin:16; Text:qstr ("Restart");           OnClicked: {Gameoverui.dismiss ();            Root.start ();            }} Button {anchors.bottom:parent.bottom;            anchors.bottommargin:40;            Anchors.left:parent.horizontalCenter;            anchors.leftmargin:16;            Text:qstr ("Quit");        OnClicked:Qt.quit ();            } springanimation {id:overanimation;            Target:gameoverui;            From:-height-1;            To:root.height * 0.125;            Spring:2;            damping:0.2;            duration:1000;            Property: "Y";            onstarted: {gameoverui.visible = true;            }} function dismiss () {y =-height-1;        Visible = false;            } function Fire (CurrentRecord, bestrecord) {current.text = CurrentRecord;            Best.text = Bestrecord;        Overanimation.start (); }    }

The target property of springanimation points to Gameoverui, which operates the Y property of Gameoverui. At first Gameoverui is not visible, when the action starts, it is set to visual (in onstarted signal processing).

The fire () method is called when the game is in progress, it launches the animation, and the game results are assigned to the Text element in the cue screen.

The specific use of springanimation, referring to QT help, or "qt Quick Core Programming ", is a very detailed introduction to the Animation class library in Qt quick.

APK settings

Create a androidmanifest.xml for Android version, double click in the project view to open the graphical editing interface, you can choose the icon you designed. Refer to "QT on Android core programming " or "Qt on Android: The whole process of text-to-detail Hello World".

Adaptive screen resolution

I spoke in the "Qt on Android: Create a scalable interface" article about how Qt on Android adapts to the changing resolution of Android phones. This is no longer a detail. Just look at the QML. How to set the size of the picture button according to the DPI code:

    ImageButton {        id:right;        Anchors.left:parent.horizontalCenter;        Anchors.leftmargin:12;        Anchors.top:problem.bottom;        anchors.topmargin:20;        NORMALIMAGE:QT.RESOLVEDURL ("Res/right_normal.png");        PRESSEDIMAGE:QT.RESOLVEDURL ("Res/right_selected.png");        Width:root.dpiFactor *;        Height:root.dpiFactor *;        OnClicked:root.check (True);    }

As you can see, I set the width of the right button to Root.dpifactor * 64. 64 is the width of the picture, in pixels. Dpifactor from Sizeutil:

Qreal sizeutil::d pifactor () {    QScreen *screen = Qapp->primaryscreen ();    return Screen->logicaldotsperinch ()/72;}

this is your ticket. Pro: Blog Star selection, click Vote I vote, thank you . If you have voted, you can also point oh, every day can cast a vote.

Well, it's over. Complete Project code download: Click to download .


--------

Look back at my QT Quick Series articles:

    • About Qt Quick
    • QML Language Basics
    • Qt Quick's Hello World text
    • Qt Quick Simple Tutorial
    • The signal and slot of Qt Quick event processing
    • Qt Quick Event Processing mouse, keyboard, timer
    • Pinch scaling and rotation of Qt Quick event processing
    • Qt Quick component and Object dynamic creation
    • Introduction to Qt Quick layout
    • Qt Quick's QML and C + + mixed programming
    • Qt Quick Image Processing example of beauty 美图秀秀 (with source download)
    • Qt Quick's Pathview detailed
    • Qt Quick Example Digging avatar
    • A file viewer for the Qt quick Synthesis instance
    • QT Quick Debug Display code line number
    • Qt Quick implementation of graffiti program
    • Qt Quick Play GIF animation
    • Drag and drop in Qt Quick (drag and drop)
    • The use of Animatedsprite in Qt quick
    • The particle system in Qt quick

Qt Quick implements the crazy arithmetic game

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.