Evgenii Legotckoi
Evgenii LegotckoiJuly 14, 2016, 5 a.m.

Game on QML - Lesson 2. Adding traces of shots and points system

After the game arena and targets were made and added, it is time to implement the targets hit, misses and charging system and cheating points.

Scoring system will be as follows:

  • In the case of near misses, I propose to make the traces of bullet holes, a few species, and cheating on one point with a game account.
  • In the case of the disappearance of the target on it without falling also make cheating a point from the game account.
  • In the case of hitting the target charge between one and five points depending on how close to the hit had given.

The score will be displayed at the top of the playing field.

Project structure

To achieve this you will need ideas, except the modification of the file, add the following files:

  • InfoBar.qml - that will display information about the account;
  • Bullet.qml - file describing the type of bullet holes;
  • bullet-1.png, bullet-2.png, bullet-3.png, bullet-4.png, bullet-5.png, bullet-6.png - files with images of bullet holes;

Possible bullet holes are placed in the graphics folder to the same target image has been transferred.


Images of bullet holes

For a variety of several types of bullet holes similar to this will be applied.

GameArea.qml

Before proceeding to the consideration of the contents of the new file, refer to the changed content GameArea.qml file, as well as logical cores on javascript in logic.js file.

The main innovation here is the emergence of property scores for scoring, and the emergence InfoBar handler mouse clicks within the gaming arena.

Scores property contains the current scores and its value is passed to the property scores in infoBar to visualize the current account of the player.

When clicking on the gaming arena, which is equivalent to slip, bullet hole created object and per unit decreases the current account. A bullet hole is created in the same way as the creation of targets realized in the last lesson, ie using Logic logic core, which is in logic.js file.

import QtQuick 2.7
import "logic.js" as Logic

Rectangle {
    id: grid

    ...

    property int scores: 0      

    ...

    InfoBar {
        id: infoBar
        scores: grid.scores
    }

    // Create a trail of bullets when you click on the game arena
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Logic.createBullet(grid, mouse.x, mouse.y)
            grid.scores--;
        }
    }

    ...
}

logic.js

The core logic of the game will add only the creation of bullet holes. Processing logic hit the targets will be added in the file that describes the target.

... 

// Create a template for the bullet
var bulletComponent = Qt.createComponent("Bullet.qml");

...

// Create a trail of bullets
function createBullet(parent, x, y)
{
    bulletComponent.createObject(parent, {"x": x, "y": y});
}

...

InfoBar.qml

InfoBar is a conventional RowLayout , which is nailed to the upper edge of the playing area, and stretched by its width. Current account will be displayed in a text field with id: scores . To set up external access to the text property of the text field, you must use the property alias.

import QtQuick 2.7
import QtQuick.Layouts 1.1

RowLayout {
    height: 40
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.top: parent.top
    anchors.leftMargin: 6
    anchors.rightMargin: 6
    spacing: 6
    z: 100

    // This property sets the access to the text field, 
    // in which the current scores will be established
    property alias scores: scores.text

    Text {
        text: qsTr("Scores")

        font.pixelSize: 20
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignHCenter
    }

    Text {
        // A text field with the current score
        id: scores

        font.pixelSize: 20
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignHCenter
    }

    // Spacer, which RowLayout will move the text field to the left edge of the InfoBar
    Item {
        Layout.fillHeight: true
        Layout.fillWidth: true
    }
}

Bullet.qml

Behavior bullet hole similar to the behavior of the target. The lifetime of the bullet hole is limited, and after the disappearance of the object is destroyed. The difference is, that is the offset coordinates (0, 0) in the middle of the object to the center of the object coincides exactly with the center point, which was committed cliques. A difference is also that in an array of object image from which to create a random selection is performed appearance bullet hole.

import QtQuick 2.7
import QtQuick.Window 2.2
import "logic.js" as Logic

Image {
    id: root
    width: 40
    height: 40

    // Set position coordinates (0, 0) in the center of the image
    transform: Translate {
        x: -width / 2
        y: -height / 2
    }

    // Set a list of possible array of bullets shot images
    property variant bullets: ["graphics/bullet-1.png", "graphics/bullet-2.png", "graphics/bullet-3.png",
                               "graphics/bullet-4.png", "graphics/bullet-5.png", "graphics/bullet-6.png"]

    // When you create an object, select a random image
    source: bullets[Logic.getRandomRound(0, 5)]

    // The timer that will count down a random value from 3500 to 10000 ms 
    // and after the disappearance of the run trace of bullets
    Timer {
        interval: Logic.getRandomRound(3500, 10000); running: true; repeat: false
        onTriggered: root.opacity = 0.0
    }

    // When the image is clear. we will destroy the object itself
    onOpacityChanged: {
        if (opacity == 0.0) {
            root.destroy()
        }
    }

    // Set the behavior of the animation properties of the object transparency
    Behavior on opacity { PropertyAnimation { duration: 100 } }
}

Target.qml

As you can see, there are five fields in which we assign a different value from 1 to 5 points.

In order to correctly calculate the hit on these areas, we need to apply the Pythagorean theorem. Remember? Of course the school trigonometry. The square of the hypotenuse equals the sum of the squares of cathetuses.

[latex]a 2 + b 2 = c^2[/latex]

So, this is the hypotenuse will range deflection hit the target from the center, well, the fact of getting on a given area will determine the radius of the circle, starting from the smaller circle. These checks are carried out in isHit() function declared in this file.

Also nuance here is that the target image is placed in the square, so that the region and also click the square, so if the click falls outside the scope of the great circle of the target, then we return 0 and pass click on in the gaming arena. To do this, you need to install propagateComposedEvents to true and prohibit accept mouse events, then it will be held in the lower lying objects to the coordinate z.

Also, do not forget to reduce the per unit expense of the game, if the target disappeared by itself without affecting the player. This is accomplished through a shared object from the logical core game, which stores the state of the gaming arena. That is, through Logic.gameState.scores.

import QtQuick 2.7
import "logic.js" as Logic

Image {
    id: root

    ...

    // When the image is clear. we will destroy the object itself
    onOpacityChanged: {
        if (opacity == 0.0) {
            Logic.gameState.scores--
            Logic.destroyTarget(row, col)
            root.destroy()
        }
    }

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        // This property determines whether the click event transmitted in lower lying elements,
        // ie those on the z-coordinate is below target
        propagateComposedEvents: true
        onClicked: {
            var scores =  isHit(root.width/2, root.height/2, mouse.x, mouse.y);
            if (scores != 0) {
                // If the score is not zero, then we fix hit
                // Increase score and destroy the target
                Logic.gameState.scores += scores;
                Logic.destroyTarget(row, col);
                root.destroy();
            } else {
                // Otherwise, pass the click event in the lower lying elements along z
                mouse.accepted = false;
            }
        }
    }

    ...

    // Checking on the target hit.
    // Check the length of the line from the center to the point at the target hit
    // Depending on the length of the line relative to the radius of circles 5, which consists of the target
    // We determine how many points we get for hitting
    // a, b - the coordinates of the target center
    // x, y - coordinates of the point of hit
    function isHit(a, b, x, y)
    {
        var length = Math.sqrt(Math.pow(Math.abs(a - x), 2) + Math.pow(Math.abs(b - y), 2));
        if (length <= 5.6) {
            return 5;
        } else if (length <= 11.2) {
            return 4;
        } else if (length <= 16.8) {
            return 3;
        } else if (length <= 22.4) {
            return 2;
        } else if (length <= 28) {
            return 1;
        } else {
            // In this case, we were in MouseArea zone
            // which is a rectangle, but missed
            // at the target, which is a disk
            return 0;
        }
    }
}

Conclusion

Now we have the expense and appearance of the application is as follows.

Download the source of Game sample on QML from GitHub

The entire series of lessons

Video

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 11:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 11:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 11:35 a.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 12:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 2:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks