Evgenii Legotckoi
July 14, 2016, 3 p.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.

  1. import QtQuick 2.7
  2. import "logic.js" as Logic
  3.  
  4. Rectangle {
  5. id: grid
  6.  
  7. ...
  8.  
  9. property int scores: 0
  10.  
  11. ...
  12.  
  13. InfoBar {
  14. id: infoBar
  15. scores: grid.scores
  16. }
  17.  
  18. // Create a trail of bullets when you click on the game arena
  19. MouseArea {
  20. anchors.fill: parent
  21. onClicked: {
  22. Logic.createBullet(grid, mouse.x, mouse.y)
  23. grid.scores--;
  24. }
  25. }
  26.  
  27. ...
  28. }

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.

  1. ...
  2.  
  3. // Create a template for the bullet
  4. var bulletComponent = Qt.createComponent("Bullet.qml");
  5.  
  6. ...
  7.  
  8. // Create a trail of bullets
  9. function createBullet(parent, x, y)
  10. {
  11. bulletComponent.createObject(parent, {"x": x, "y": y});
  12. }
  13.  
  14. ...

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.

  1. import QtQuick 2.7
  2. import QtQuick.Layouts 1.1
  3.  
  4. RowLayout {
  5. height: 40
  6. anchors.left: parent.left
  7. anchors.right: parent.right
  8. anchors.top: parent.top
  9. anchors.leftMargin: 6
  10. anchors.rightMargin: 6
  11. spacing: 6
  12. z: 100
  13.  
  14. // This property sets the access to the text field,
  15.   // in which the current scores will be established
  16. property alias scores: scores.text
  17.  
  18. Text {
  19. text: qsTr("Scores")
  20.  
  21. font.pixelSize: 20
  22. verticalAlignment: Text.AlignVCenter
  23. horizontalAlignment: Text.AlignHCenter
  24. }
  25.  
  26. Text {
  27. // A text field with the current score
  28. id: scores
  29.  
  30. font.pixelSize: 20
  31. verticalAlignment: Text.AlignVCenter
  32. horizontalAlignment: Text.AlignHCenter
  33. }
  34.  
  35. // Spacer, which RowLayout will move the text field to the left edge of the InfoBar
  36. Item {
  37. Layout.fillHeight: true
  38. Layout.fillWidth: true
  39. }
  40. }

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.

  1. import QtQuick 2.7
  2. import QtQuick.Window 2.2
  3. import "logic.js" as Logic
  4.  
  5. Image {
  6. id: root
  7. width: 40
  8. height: 40
  9.  
  10. // Set position coordinates (0, 0) in the center of the image
  11. transform: Translate {
  12. x: -width / 2
  13. y: -height / 2
  14. }
  15.  
  16. // Set a list of possible array of bullets shot images
  17. property variant bullets: ["graphics/bullet-1.png", "graphics/bullet-2.png", "graphics/bullet-3.png",
  18. "graphics/bullet-4.png", "graphics/bullet-5.png", "graphics/bullet-6.png"]
  19.  
  20. // When you create an object, select a random image
  21. source: bullets[Logic.getRandomRound(0, 5)]
  22.  
  23. // The timer that will count down a random value from 3500 to 10000 ms
  24.   // and after the disappearance of the run trace of bullets
  25. Timer {
  26. interval: Logic.getRandomRound(3500, 10000); running: true; repeat: false
  27. onTriggered: root.opacity = 0.0
  28. }
  29.  
  30. // When the image is clear. we will destroy the object itself
  31. onOpacityChanged: {
  32. if (opacity == 0.0) {
  33. root.destroy()
  34. }
  35. }
  36.  
  37. // Set the behavior of the animation properties of the object transparency
  38. Behavior on opacity { PropertyAnimation { duration: 100 } }
  39. }

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.

  1. import QtQuick 2.7
  2. import "logic.js" as Logic
  3.  
  4. Image {
  5. id: root
  6.  
  7. ...
  8.  
  9. // When the image is clear. we will destroy the object itself
  10. onOpacityChanged: {
  11. if (opacity == 0.0) {
  12. Logic.gameState.scores--
  13. Logic.destroyTarget(row, col)
  14. root.destroy()
  15. }
  16. }
  17.  
  18. MouseArea {
  19. id: mouseArea
  20. anchors.fill: parent
  21. // This property determines whether the click event transmitted in lower lying elements,
  22.   // ie those on the z-coordinate is below target
  23. propagateComposedEvents: true
  24. onClicked: {
  25. var scores = isHit(root.width/2, root.height/2, mouse.x, mouse.y);
  26. if (scores != 0) {
  27. // If the score is not zero, then we fix hit
  28. // Increase score and destroy the target
  29. Logic.gameState.scores += scores;
  30. Logic.destroyTarget(row, col);
  31. root.destroy();
  32. } else {
  33. // Otherwise, pass the click event in the lower lying elements along z
  34. mouse.accepted = false;
  35. }
  36. }
  37. }
  38.  
  39. ...
  40.  
  41. // Checking on the target hit.
  42. // Check the length of the line from the center to the point at the target hit
  43. // Depending on the length of the line relative to the radius of circles 5, which consists of the target
  44. // We determine how many points we get for hitting
  45. // a, b - the coordinates of the target center
  46. // x, y - coordinates of the point of hit
  47. function isHit(a, b, x, y)
  48. {
  49. var length = Math.sqrt(Math.pow(Math.abs(a - x), 2) + Math.pow(Math.abs(b - y), 2));
  50. if (length <= 5.6) {
  51. return 5;
  52. } else if (length <= 11.2) {
  53. return 4;
  54. } else if (length <= 16.8) {
  55. return 3;
  56. } else if (length <= 22.4) {
  57. return 2;
  58. } else if (length <= 28) {
  59. return 1;
  60. } else {
  61. // In this case, we were in MouseArea zone
  62. // which is a rectangle, but missed
  63. // at the target, which is a disk
  64. return 0;
  65. }
  66. }
  67. }

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

Recommended articles on this topic

By article asked0question(s)

0

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup