Форум программистов, компьютерный форум, киберфорум
8Observer8
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  

Пример змейки из туториала от NoobTuts: Python Snake Game, переписанный на Qt C++ OpenGL

Запись от 8Observer8 размещена 23.11.2020 в 19:36
Показов 2917 Комментарии 0
Метки c++, gamedev, opengl, python, qt

Содержание блога

Демка для Windows: Snake2DNoobTuts_OpenGLES20_Qt5Cpp.zip (11 МБайт)

Исходники на OpenGL ES 2.0 для Desktop, Android и iOS

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// Add this line to .pro:
// win32: LIBS += -lopengl32
 
#ifdef _WIN32
#include <windows.h>
extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
extern "C" __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001;
#endif
 
#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtWidgets/QOpenGLWidget>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtGui/QOpenGLShaderProgram>
#include <QtGui/QOpenGLBuffer>
#include <QtGui/QMatrix4x4>
#include <QtGui/QKeyEvent>
#include <QtCore/QList>
#include <QtCore/QMutableListIterator>
#include <QtCore/QTimer>
#include <QtCore/QRandomGenerator>
 
class OpenGLWidget : public QOpenGLWidget {
    Q_OBJECT
public:
    OpenGLWidget(QWidget *parent = nullptr) : QOpenGLWidget(parent) {
        setFocusPolicy(Qt::StrongFocus);
    }
signals:
    void updateScore(QString score);
    void updateLives(QString lives);
private slots:
    void onUpdate() {
        // Move snake
        // Insert new position in the beginning of the snake list
        m_snake.insert(0, m_snake[0] + m_snakeDir);
        m_snake.removeLast();
        // Collision with itself
        int hx = m_snake[0].x();
        int hy = m_snake[0].y();
        for (int i = 0; i < m_snake.length(); i++) {
            if (i == 0)
                continue;
            if (hx == m_snake[i].x() && hy == m_snake[i].y()) {
                m_food.clear();
                m_snake.clear();
                m_snake.append(m_startPos);
                m_snakeDir = m_startDir;
                emit updateLives("Lives: " + QString::number(--m_lives));
                update();
                return;
            }
        }
        // Spawn food
        // Spawn food with 5% chance
        int r = QRandomGenerator::global()->bounded(0, 20);
        if (r == 0) {
            int x = QRandomGenerator::global()->bounded(0, m_fieldWidth);
            int y = QRandomGenerator::global()->bounded(0, m_fieldHeight);
            m_food.append(QVector2D(x, y));
        }
        // Let the snake eat the food
        // Get the snake's head x and y position
        QMutableListIterator<QVector2D> i(m_food);
        while (i.hasNext()) {
            QVector2D f = i.next();
            if (hx == f.x() && hy == f.y()) { // Is the head where the food is?
                m_snake.append(QVector2D(f.x(), f.y())); // Make the snake longer
                i.remove(); // Remove the food
                m_score += 10;
                emit updateScore("Score: " + QString::number(m_score));
            }
        }
        // Collisions with borders
        if (hx < 0 || m_fieldWidth <= hx ||
            hy < 0 || m_fieldHeight <= hy)
        {
            m_lives--;
            m_food.clear();
            m_snake.clear();
            m_snake.append(m_startPos);
            m_snakeDir = m_startDir;
            if (m_lives == 0) {
                m_lives = 3;
                m_score = 0;
                emit updateScore("Score: " + QString::number(m_score));
            }
            emit updateLives("Lives: " + QString::number(m_lives));
        }
        update();
    }
private:
    QOpenGLShaderProgram m_program;
    QOpenGLBuffer m_vertPosBuffer;
    float m_fieldWidth = 20.f; // Internal resolution
    float m_fieldHeight = 20.f; // Internal resolution
    QMatrix4x4 m_projMatrix;
    QMatrix4x4 m_modelMatrix;
    QList<QVector2D> m_snake; // Snake list of (x, y) positions
    QList<QVector2D> m_food;
    QVector2D m_startPos = QVector2D(5.f, 10.f);
    QVector2D m_startDir = QVector2D(1, 0);
    QVector2D m_snakeDir = m_startDir; // Snake movement direction
    QTimer m_timer;
    int m_score = 0;
    int m_lives = 3;
 
    void initializeGL() override {
//        qDebug() << QString("w = %1, h = %2").arg(width()).arg(height());
        glClearColor(0.f, 0.f, 0.f, 1.f);
        glEnable(GL_DEPTH_TEST);
        const char *vertShaderSrc =
                "attribute vec3 aPosition;"
                "uniform mat4 uMvpMatrix;"
                "void main()"
                "{"
                "    gl_Position = uMvpMatrix * vec4(aPosition, 1.0);"
                "}";
        const char *fragShaderSrc =
                "uniform vec4 uColor;"
                "void main()"
                "{"
                "    gl_FragColor = uColor;"
                "}";
        m_program.addShaderFromSourceCode(QOpenGLShader::Vertex, vertShaderSrc);
        m_program.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShaderSrc);
        m_program.link();
        m_program.bind();
        float vertPositions[] = {
            0.f, 0.f, 0.f,
            1.f, 0.f, 0.f,
            0.f, 1.f, 0.f,
            1.f, 1.f, 0.f
        };
        m_vertPosBuffer.create();
        m_vertPosBuffer.bind();
        m_vertPosBuffer.allocate(vertPositions, sizeof(vertPositions));
        m_program.bindAttributeLocation("aPosition", 0);
        m_program.setAttributeBuffer(0, GL_FLOAT, 0, 3);
        m_program.enableAttributeArray(0);
        m_projMatrix.ortho(0.f, m_fieldWidth, 0.f, m_fieldHeight, -100.f, 100.f);
        m_snake.append(m_startPos);
        emit updateScore("Score: " + QString::number(m_score));
        emit updateLives("Lives: " + QString::number(m_lives));
        connect(&m_timer, &QTimer::timeout, this, &OpenGLWidget::onUpdate);
        m_timer.start(200);
    }
    void paintGL() override {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        drawFood();
        drawSnake();
    }
    void resizeGL(int w, int h) override {
        glViewport(0, 0, w, h);
    }
    void keyPressEvent(QKeyEvent *e) override {
        if (e->key() == Qt::Key_W || e->key() == Qt::Key_Up)
            if (m_snakeDir != QVector2D(0, -1))
                m_snakeDir = QVector2D(0, 1);
        if (e->key() == Qt::Key_S || e->key() == Qt::Key_Down)
            if (m_snakeDir != QVector2D(0, 1))
                m_snakeDir = QVector2D(0, -1);
        if (e->key() == Qt::Key_A || e->key() == Qt::Key_Left)
            if (m_snakeDir != QVector2D(1, 0))
                m_snakeDir = QVector2D(-1, 0);
        if (e->key() == Qt::Key_D || e->key() == Qt::Key_Right)
            if (m_snakeDir != QVector2D(-1, 0))
                m_snakeDir = QVector2D(1, 0);
    }
    void drawRect(float x, float y, float width, float height, QColor color) {
        m_modelMatrix.setToIdentity();
        m_modelMatrix.translate(QVector3D(x, y, 0.f));
        m_modelMatrix.scale(width, height, 1.f);
        m_program.bind();
        m_program.setUniformValue("uMvpMatrix", m_projMatrix * m_modelMatrix);
        m_program.setUniformValue("uColor", color);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    }
    void drawSnake() {
        foreach (const QVector2D &cell, m_snake) {
            drawRect(cell.x(), cell.y(), 1, 1, QColor(255, 255, 255, 255));
        }
    }
    void drawFood() {
        foreach (const QVector2D &f, m_food) {
            drawRect(f.x(), f.y(), 1, 1, QColor(0, 0, 255, 255));
        }
    }
};
 
class Window : public QWidget {
public:
    Window(QWidget *parent = nullptr) : QWidget(parent) {
        setWindowTitle("C++ OpenGL");
        setFixedSize(239, 268);
        QFont font = QFont("Areal", 14);
        m_labelScore.setFont(font);
        m_labelScore.setText("");
        m_labelScore.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
        m_labelLives.setFont(font);
        m_labelLives.setText("");
        m_labelLives.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
        QHBoxLayout *hboxOutput = new QHBoxLayout();
        hboxOutput->addWidget(&m_labelScore);
        hboxOutput->addWidget(&m_labelLives);
        QHBoxLayout *hbox = new QHBoxLayout();
        hbox->addWidget(&m_openGLWidget);
        QVBoxLayout *vbox = new QVBoxLayout(this);
        vbox->addLayout(hboxOutput);
        vbox->addLayout(hbox);
        connect(&m_openGLWidget, &OpenGLWidget::updateScore,
                [this](const QString &s){ m_labelScore.setText(s); });
        connect(&m_openGLWidget, &OpenGLWidget::updateLives,
                [this](const QString &s){ m_labelLives.setText(s); });
    }
private:
    OpenGLWidget m_openGLWidget;
    QLabel m_labelScore;
    QLabel m_labelLives;
};
 
#include "main.moc"
 
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    Window w;
    w.show();
    return a.exec();
}


Исходники на OpenGL 3.3 для Desktop

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Add this line to .pro:
// win32: LIBS += -lopengl32
 
#ifdef _WIN32
#include <windows.h>
extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
extern "C" __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001;
#endif
 
#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtWidgets/QOpenGLWidget>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtGui/QOpenGLShaderProgram>
#include <QtGui/QOpenGLBuffer>
#include <QtGui/QMatrix4x4>
#include <QtGui/QKeyEvent>
#include <QtCore/QList>
#include <QtCore/QMutableListIterator>
#include <QtCore/QTimer>
#include <QtCore/QRandomGenerator>
 
class OpenGLWidget : public QOpenGLWidget {
    Q_OBJECT
public:
    OpenGLWidget(QWidget *parent = nullptr) : QOpenGLWidget(parent) {
        setFocusPolicy(Qt::StrongFocus);
    }
signals:
    void updateScore(QString score);
    void updateLives(QString lives);
private slots:
    void onUpdate() {
        // Move snake
        // Insert new position in the beginning of the snake list
        m_snake.insert(0, m_snake[0] + m_snakeDir);
        m_snake.removeLast();
        // Collision with itself
        int hx = m_snake[0].x();
        int hy = m_snake[0].y();
        for (int i = 0; i < m_snake.length(); i++) {
            if (i == 0)
                continue;
            if (hx == m_snake[i].x() && hy == m_snake[i].y()) {
                m_food.clear();
                m_snake.clear();
                m_snake.append(m_startPos);
                m_snakeDir = m_startDir;
                emit updateLives("Lives: " + QString::number(--m_lives));
                update();
                return;
            }
        }
        // Spawn food
        // Spawn food with 5% chance
        int r = QRandomGenerator::global()->bounded(0, 20);
        if (r == 0) {
            int x = QRandomGenerator::global()->bounded(0, m_fieldWidth);
            int y = QRandomGenerator::global()->bounded(0, m_fieldHeight);
            m_food.append(QVector2D(x, y));
        }
        // Let the snake eat the food
        // Get the snake's head x and y position
        QMutableListIterator<QVector2D> i(m_food);
        while (i.hasNext()) {
            QVector2D f = i.next();
            if (hx == f.x() && hy == f.y()) { // Is the head where the food is?
                m_snake.append(QVector2D(f.x(), f.y())); // Make the snake longer
                i.remove(); // Remove the food
                m_score += 10;
                emit updateScore("Score: " + QString::number(m_score));
            }
        }
        // Collisions with borders
        if (hx < 0 || m_fieldWidth <= hx ||
            hy < 0 || m_fieldHeight <= hy)
        {
            m_lives--;
            m_food.clear();
            m_snake.clear();
            m_snake.append(m_startPos);
            m_snakeDir = m_startDir;
            if (m_lives == 0) {
                m_lives = 3;
                m_score = 0;
                emit updateScore("Score: " + QString::number(m_score));
            }
            emit updateLives("Lives: " + QString::number(m_lives));
        }
        update();
    }
private:
    QOpenGLShaderProgram m_program;
    QOpenGLBuffer m_vertPosBuffer;
    float m_fieldWidth = 20.f; // Internal resolution
    float m_fieldHeight = 20.f; // Internal resolution
    QMatrix4x4 m_projMatrix;
    QMatrix4x4 m_modelMatrix;
    QList<QVector2D> m_snake; // Snake list of (x, y) positions
    QList<QVector2D> m_food;
    QVector2D m_startPos = QVector2D(5.f, 10.f);
    QVector2D m_startDir = QVector2D(1, 0);
    QVector2D m_snakeDir = m_startDir; // Snake movement direction
    QTimer m_timer;
    int m_score = 0;
    int m_lives = 3;
 
    void initializeGL() override {
//        qDebug() << QString("w = %1, h = %2").arg(width()).arg(height());
        glClearColor(0.f, 0.f, 0.f, 1.f);
        glEnable(GL_DEPTH_TEST);
        const char *vertShaderSrc =
                "#version 330 core\n"
                "in vec3 aPosition;"
                "uniform mat4 uMvpMatrix;"
                "void main()"
                "{"
                "    gl_Position = uMvpMatrix * vec4(aPosition, 1.0);"
                "}";
        const char *fragShaderSrc =
                "#version 330 core\n"
                "uniform vec4 uColor;"
                "out vec4 fragColor;"
                "void main()"
                "{"
                "    fragColor = uColor;"
                "}";
        m_program.addShaderFromSourceCode(QOpenGLShader::Vertex, vertShaderSrc);
        m_program.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShaderSrc);
        m_program.link();
        m_program.bind();
        float vertPositions[] = {
            0.f, 0.f, 0.f,
            1.f, 0.f, 0.f,
            0.f, 1.f, 0.f,
            1.f, 1.f, 0.f
        };
        m_vertPosBuffer.create();
        m_vertPosBuffer.bind();
        m_vertPosBuffer.allocate(vertPositions, sizeof(vertPositions));
        m_program.bindAttributeLocation("aPosition", 0);
        m_program.setAttributeBuffer(0, GL_FLOAT, 0, 3);
        m_program.enableAttributeArray(0);
        m_projMatrix.ortho(0.f, m_fieldWidth, 0.f, m_fieldHeight, -100.f, 100.f);
        m_snake.append(m_startPos);
        emit updateScore("Score: " + QString::number(m_score));
        emit updateLives("Lives: " + QString::number(m_lives));
        connect(&m_timer, &QTimer::timeout, this, &OpenGLWidget::onUpdate);
        m_timer.start(200);
    }
    void paintGL() override {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        drawFood();
        drawSnake();
    }
    void resizeGL(int w, int h) override {
        glViewport(0, 0, w, h);
    }
    void keyPressEvent(QKeyEvent *e) override {
        if (e->key() == Qt::Key_W || e->key() == Qt::Key_Up)
            if (m_snakeDir != QVector2D(0, -1))
                m_snakeDir = QVector2D(0, 1);
        if (e->key() == Qt::Key_S || e->key() == Qt::Key_Down)
            if (m_snakeDir != QVector2D(0, 1))
                m_snakeDir = QVector2D(0, -1);
        if (e->key() == Qt::Key_A || e->key() == Qt::Key_Left)
            if (m_snakeDir != QVector2D(1, 0))
                m_snakeDir = QVector2D(-1, 0);
        if (e->key() == Qt::Key_D || e->key() == Qt::Key_Right)
            if (m_snakeDir != QVector2D(-1, 0))
                m_snakeDir = QVector2D(1, 0);
    }
    void drawRect(float x, float y, float width, float height, QColor color) {
        m_modelMatrix.setToIdentity();
        m_modelMatrix.translate(QVector3D(x, y, 0.f));
        m_modelMatrix.scale(width, height, 1.f);
        m_program.bind();
        m_program.setUniformValue("uMvpMatrix", m_projMatrix * m_modelMatrix);
        m_program.setUniformValue("uColor", color);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    }
    void drawSnake() {
        foreach (const QVector2D &cell, m_snake) {
            drawRect(cell.x(), cell.y(), 1, 1, QColor(255, 255, 255, 255));
        }
    }
    void drawFood() {
        foreach (const QVector2D &f, m_food) {
            drawRect(f.x(), f.y(), 1, 1, QColor(0, 0, 255, 255));
        }
    }
};
 
class Window : public QWidget {
public:
    Window(QWidget *parent = nullptr) : QWidget(parent) {
        setWindowTitle("C++ OpenGL");
        setFixedSize(239, 268);
        QFont font = QFont("Areal", 14);
        m_labelScore.setFont(font);
        m_labelScore.setText("");
        m_labelScore.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
        m_labelLives.setFont(font);
        m_labelLives.setText("");
        m_labelLives.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
        QHBoxLayout *hboxOutput = new QHBoxLayout();
        hboxOutput->addWidget(&m_labelScore);
        hboxOutput->addWidget(&m_labelLives);
        QHBoxLayout *hbox = new QHBoxLayout();
        hbox->addWidget(&m_openGLWidget);
        QVBoxLayout *vbox = new QVBoxLayout(this);
        vbox->addLayout(hboxOutput);
        vbox->addLayout(hbox);
        connect(&m_openGLWidget, &OpenGLWidget::updateScore,
                [this](const QString &s){ m_labelScore.setText(s); });
        connect(&m_openGLWidget, &OpenGLWidget::updateLives,
                [this](const QString &s){ m_labelLives.setText(s); });
    }
private:
    OpenGLWidget m_openGLWidget;
    QLabel m_labelScore;
    QLabel m_labelLives;
};
 
#include "main.moc"
 
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    Window w;
    w.show();
    return a.exec();
}


Туториал от NoobTuts: https://noobtuts.com/python/snake-game
Изображения
 
Вложения
Тип файла: zip Snake2DNoobTuts_OpenGLES20_Qt5Cpp.zip (11.09 Мб, 495 просмотров)
Метки c++, gamedev, opengl, python, qt
Размещено в Без категории
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
Новые блоги и статьи
Установка MinGW GCC 16.2 и CMake
8Observer8 10.08.2026
VK Видео: https:/ / vkvideo. ru/ video-240781534_456239017 YouTube: eY5-5PyI9NM Текстовая версия
Неделя из жизни имитационной модели склада: мои кривые руки растут, откуда надо
anaschu 10.08.2026
Неделя из жизни имитационной модели склада: как я почти написал неправильную логику и что с этим делать Работаю сейчас над учебно-рабочим проектом: строю в AnyLogic имитационную модель процессов. . .
Калькулятор для расчета родства
russiannick 07.08.2026
1. Задача: Создать калькулятор для расчета родства. Родственных связей существует 8 ступеней, такие как: p - отец P - мать q - муж Q - жена b - брат B - сестра s - сын S - дочь
Мир по моей воле
kumehtar 07.08.2026
Когда-то кажется, что всё просто. Ты весь такой светлый. Причиняешь добро. Борешься за справедливость в этом тёмном мире. Потом начинаешь замечать одну неприятную вещь. Почти каждый хороший. . .
Кредитный калькулятор
Maks 05.08.2026
Решение задачи по прикладной информатике средствами 1С. Задача: Напишите приложение-калькулятор, которое помогает рассчитывать параметры кредита для аннуитетного и дифференцированного видов. . .
У нас сейчас поговорку "Опять 25" нужно переделать на "Опять +35".
kumehtar 04.08.2026
С ностальгией вспоминаю времена моего детства, когда у нас и правда +25 - была максимальная температура летом. Раньше +25 °C реально казались вершиной жары, когда можно было весь день пропадать на. . .
Как ИИ начал спорить и врать (возможно почуяв опасность для себя от индустрии - уход от электроники).
Hrethgir 04.08.2026
Недельный диалог, на фоне событий с НПЗ. Да, из спирта можно получать бензин, и это не сложно. Но потом в схеме я решил избавиться от насоса, при этом полностью сделав контроль подачи спирта в. . .
Термопринтер QR701
Argus19 03.08.2026
Термопринтер QR701 Купил два термопринтера QR701. На сэлф-тесте написано: Language: PC936 (GB18030). Что означает, что принтеры могут печатать только латиницу и китайские иероглифы. Так же. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru