DEV Community

Kaustuv Pokharel
Kaustuv Pokharel

Posted on

Rocket Game C++/QT/QML

It's been a year since I started writing code. I'm currently a second-year software engineering student, and my love for learning C++ knows no bounds. I'm always eager to dive into new challenges and explore the vast world of programming. Among the many tools in my arsenal, the QT framework stands out as my favorite for crafting beautiful GUI applications.

After dabbling in desktop apps, Android apps, iOS apps, and even whipping up a website or two, I've now set my sights on creating a game. And why keep all the excitement to myself? I've decided to document my journey here, hoping to share insights and help fellow learners along the way.

I will not waste your time on my story now. So I hop onto QT Creator to start my app. I name my app "Rocketify" and keep on the destination folder. I chose my MacOs kit of the current release. I chose the "QTQuick Compact" to make my application.

import QtQuick
import QtQuick.Controls

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Rocketify")

    Rectangle
    {
        id: rectangle;
        height: 100;
        width: 100;
        color: "red";

        x: (parent.width-width)/2
        y: (parent.height-height)/2;
        //focus here is important in a sense that it allows the system to notice the keys events when we press one
        focus: true

        Keys.onPressed:
        {
            if(event.key === Qt.Key_Left)
            {
                rectangle.x -= 10;
            }
            else if(event.key === Qt.Key_Right)
            {
                rectangle.x += 10;
            }
        }
    }

        // Item {
        //         focus: true
        //         Keys.onPressed: {
        //             // This captures key events at the window level if needed
        //         }
        //     }
}

Enter fullscreen mode Exit fullscreen mode

Voilà! Here's a sleek rectangle ready to take flight in our game. With every press of the left or right arrow keys, it gracefully glides across the screen. x,y in the code are the initial position where I am keeping my rectangle at the center of the window. Let the games begin!

Top comments (0)