Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.67/9: Рейтинг темы: голосов - 9, средняя оценка - 4.67
1 / 1 / 0
Регистрация: 23.06.2017
Сообщений: 153

Найти ошибку в программе работы с SDL

25.07.2017, 15:49. Показов 2224. Ответов 26
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Я написал програму которая должна выводить текст на екран. Если все в олном файле все норм работает. но я решил создать клас и немного коду туда перенести. И теперь крешится. и я не пойму почему
Хедер:
C++
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
#pragma once
 
#include <SDL.h>
#include <SDL_ttf.h>
#include <conio.h>
#include <iostream>
#include <memory>
#include <functional>
 
using SDLQuiter = std::unique_ptr<void, std::function<void(void*)>>;
using SDLWindowPointer = std::unique_ptr<SDL_Window, std::function<void(SDL_Window*)>>;
using SDLRendererPointer = std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer*)>>;
using SDLSurfacePointer = std::unique_ptr<SDL_Surface, std::function<void(SDL_Surface*)>>;
using SDLTexturePointer = std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture*)>>;
using TTFFontPointer = std::unique_ptr<TTF_Font, std::function<void(TTF_Font*)>>;
 
class RenderStartMenu 
{
public:
    RenderStartMenu();
    RenderStartMenu(SDLRendererPointer& renderer, SDLSurfacePointer& marioTextSurface, TTFFontPointer& marioTextFont, SDLTexturePointer& marioTextTexture, SDL_Rect& marioTextRect,
        SDLSurfacePointer& enterTextSurface, TTFFontPointer& enterTextFont, SDLTexturePointer& enterTextTexture, SDL_Rect& enterTextRect, const int windowWidth, const int windowHeight);
    ~RenderStartMenu();
 
private:
    SDLRendererPointer mRenderer;
    SDLSurfacePointer mMarioTextSurface;
    TTFFontPointer mMarioTextFont;
    SDLTexturePointer mMarioTextTexture;
    SDL_Rect mMarioTextRect;
    SDLSurfacePointer mEnterTextSurface;
    TTFFontPointer mEnterTextFont;
    SDLTexturePointer mEnterTextTexture;
    SDL_Rect mEnterTextRect;
    int mWindowWidth;
    int mWindowHeight;
};
СPP:
C++
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
#include "RenderStartMenu.h"
 
RenderStartMenu::RenderStartMenu()
    : mRenderer(nullptr)
    , mMarioTextSurface(nullptr)
    , mMarioTextFont(nullptr)
    , mMarioTextTexture(nullptr)
    , mMarioTextRect()
    , mEnterTextSurface(nullptr)
    , mEnterTextFont(nullptr)
    , mEnterTextTexture(nullptr)
    , mEnterTextRect()
    , mWindowWidth(0)
    , mWindowHeight(0)
{}
 
RenderStartMenu::RenderStartMenu(SDLRendererPointer& renderer, SDLSurfacePointer& marioTextSurface, TTFFontPointer& marioTextFont, SDLTexturePointer& marioTextTexture, SDL_Rect& marioTextRect,
    SDLSurfacePointer& enterTextSurface, TTFFontPointer& enterTextFont, SDLTexturePointer& enterTextTexture, SDL_Rect& enterTextRect, const int windowWidth, const int windowHeight)
    : mRenderer(renderer.get())
    , mMarioTextSurface(marioTextSurface.get())
    , mMarioTextFont(marioTextFont.get())
    , mMarioTextTexture(marioTextTexture.get())
    , mMarioTextRect(marioTextRect)
    , mEnterTextSurface(enterTextSurface.get())
    , mEnterTextFont(enterTextFont.get())
    , mEnterTextTexture(enterTextTexture.get())
    , mEnterTextRect(enterTextRect)
    , mWindowWidth(windowWidth)
    , mWindowHeight(windowHeight)
{
    if (marioTextFont == nullptr)
    {
        SDL_Log("Unable to create font: %s", TTF_GetError());
    }
 
 
 
 
    if (marioTextSurface == nullptr)
    {
        SDL_Log("Unable to create surface: %s", TTF_GetError());
    }
 
 
    if (marioTextTexture == nullptr)
    {
        SDL_Log("Unable to create texture: %s", TTF_GetError());
    }
    SDL_QueryTexture(marioTextTexture.get(), nullptr, nullptr, &marioTextRect.w, &marioTextRect.h);
    marioTextRect.x = windowWidth / 2 - marioTextRect.w / 2;
    marioTextRect.y = windowHeight / 2 - marioTextRect.h / 2 - 50;
 
 
    if (enterTextFont == nullptr)
    {
        SDL_Log("Unable to create font: %s", TTF_GetError());
    }
 
    if (enterTextSurface == nullptr)
    {
        SDL_Log("Unable to create surface: %s", TTF_GetError());
    }
 
 
    if (enterTextTexture == nullptr)
    {
        SDL_Log("Unable to create texture: %s", TTF_GetError());
    }
 
    SDL_QueryTexture(enterTextTexture.get(), nullptr, nullptr, &enterTextRect.w, &enterTextRect.h);
    enterTextRect.x = windowWidth / 2 - enterTextRect.w / 2;
    enterTextRect.y = windowHeight / 2 - enterTextRect.h / 2 + marioTextRect.h;
}
 
RenderStartMenu::~RenderStartMenu()
{
    SDL_SetRenderDrawColor(mRenderer.get(), 0, 0, 255, 0);
    SDL_RenderClear(mRenderer.get());
    SDL_RenderCopy(mRenderer.get(), mMarioTextTexture.get(), nullptr, &mMarioTextRect);
    SDL_RenderCopy(mRenderer.get(), mEnterTextTexture.get(), nullptr, &mEnterTextRect);
    SDL_RenderPresent(mRenderer.get());
}
Main:
C++
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
#include "RenderStartMenu.h"
enum class State
{
    StartMenuState,
    PlayGameState,
    EndMenuState
};
int main(int argc, char** argv)
{
    const int windowWidth = 1280;
    const int windowHeight = 720;
 
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }
    SDLQuiter sdlQuiter(nullptr, [](void*) { SDL_Quit(); });
 
    if (TTF_Init() != 0)
    {
        SDL_Log("Unable to initialize TTF: %s", TTF_GetError());
        return 1;
    }
    TTFQuiter ttfQuiter(nullptr, [](void*) { TTF_Quit(); });
 
    SDLWindowPointer window(SDL_CreateWindow(
        "Mario by ",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        windowWidth,
        windowHeight,
        SDL_WINDOW_OPENGL
    ), SDL_DestroyWindow);
    
    if (window == nullptr)
    {
        SDL_Log("Unable to created window: %s", SDL_GetError());
        return 1;
    }
    SDLRendererPointer renderer(SDL_CreateRenderer(window.get(), -1,
        SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE), SDL_DestroyRenderer);
 
    if (renderer == nullptr)
    {
        SDL_Log("Failed to create renderer: %s", SDL_GetError());
        return 1;
    }
 
    TTFFontPointer marioTextFont(TTF_OpenFont("Resources/Fonts/Arial.TTF", 130), TTF_CloseFont);
    SDL_Color textColor = { 255, 255, 255, 255 };
    SDLSurfacePointer marioTextSurface(TTF_RenderText_Solid(marioTextFont.get(), "Mario", textColor), SDL_FreeSurface);
    SDLTexturePointer marioTextTexture(SDL_CreateTextureFromSurface(renderer.get(), marioTextSurface.get()), SDL_DestroyTexture);
    SDL_Rect marioTextRect;
 
 
    TTFFontPointer enterTextFont(TTF_OpenFont("Resources/Fonts/Arial.TTF", 30), TTF_CloseFont);
    SDLSurfacePointer enterTextSurface(TTF_RenderText_Solid(enterTextFont.get(), "Press Space to enter", textColor), SDL_FreeSurface);
    SDLTexturePointer enterTextTexture(SDL_CreateTextureFromSurface(renderer.get(), enterTextSurface.get()), SDL_DestroyTexture);
    SDL_Rect enterTextRect;
 
    SDL_Event event;
    State state = State::StartMenuState;
    for (bool runGame = true; runGame; )
    {
        
        
        if (state == State::StartMenuState)
        {
        /*Ось тут выклыкаю свой клас  RenderStartMenu*/
               RenderStartMenu renderStartMenu(renderer, marioTextSurface, marioTextFont, marioTextTexture, marioTextRect,
                enterTextSurface, enterTextFont, enterTextTexture, enterTextRect, windowWidth, windowHeight);
            
        else if (state == State::PlayGameState)
        {
            
        }
        else if (state == State::EndMenuState)
        {
            
        }
    }
    return 0;
}
0
Лучшие ответы (1)
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
25.07.2017, 15:49
Ответы с готовыми решениями:

SDL - помогите найти ошибку в коде
Ребят, начал изучать SDL. Такая параша #include &lt;SDL.h&gt; int main () { SDL_Init (SDL_INIT_VIDEO | |SDL_INIT_VIDEO); if (...

Найти ошибку в программе: в visual studio выдает ошибку
#include &lt;math.h&gt; #include &lt;conio.h&gt; #include &lt;iostream&gt; using namespace std; int main() { double x, E, ypred, y, S; ...

Не могу найти ошибку в программе(для просмотра картинок):кнопка НАЗАД не работает(не становится активной) Найдите ошибку.

26
1 / 1 / 0
Регистрация: 23.06.2017
Сообщений: 153
26.07.2017, 01:16  [ТС]
Студворк — интернет-сервис помощи студентам
nonedark2008, ок. я услышал Вас, но в том состоянии как зараз есть. что тут не правильно , почему не правильно работает? Так как если я зараз начну все ломать и переделывать снова все пойдет под косяк.

Добавлено через 10 минут
nonedark2008,
Переделал:
C++
1
2
3
4
5
6
7
8
9
10
11
SDLRendererPointer& mRenderer;
    SDLSurfacePointer& mMarioTextSurface;
    TTFFontPointer& mMarioTextFont;
    SDLTexturePointer& mMarioTextTexture;
    SDL_Rect& mMarioTextRect;
    SDLSurfacePointer& mEnterTextSurface;
    TTFFontPointer& mEnterTextFont;
    SDLTexturePointer& mEnterTextTexture;
    SDL_Rect& mEnterTextRect;
    int mWindowWidth;
    int mWindowHeight;
Добавлено через 24 секунды
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
RenderStartMenu::RenderStartMenu(SDLRendererPointer& renderer, SDLSurfacePointer& marioTextSurface, TTFFontPointer& marioTextFont, SDLTexturePointer& marioTextTexture, SDL_Rect& marioTextRect,
    SDLSurfacePointer& enterTextSurface, TTFFontPointer& enterTextFont, SDLTexturePointer& enterTextTexture, SDL_Rect& enterTextRect, const int windowWidth, const int windowHeight)
    : mRenderer(renderer)
    , mMarioTextSurface(marioTextSurface)
    , mMarioTextFont(marioTextFont)
    , mMarioTextTexture(marioTextTexture)
    , mMarioTextRect(marioTextRect)
    , mEnterTextSurface(enterTextSurface)
    , mEnterTextFont(enterTextFont)
    , mEnterTextTexture(enterTextTexture)
    , mEnterTextRect(enterTextRect)
    , mWindowWidth(windowWidth)
    , mWindowHeight(windowHeight)
Добавлено через 2 минуты
УРАААА. Все работает))) Спасибоnonedark2008, за помощь
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
26.07.2017, 01:18
dimaSlon, рад за тебя. Не забудь, что в остальных классах у тебя аналогичная проблема.
0
1 / 1 / 0
Регистрация: 23.06.2017
Сообщений: 153
26.07.2017, 01:29  [ТС]
nonedark2008, я вынес в деструктор код
C++
1
2
3
4
5
6
7
8
RenderStartMenu::~RenderStartMenu() 
{
    SDL_SetRenderDrawColor(mRenderer.get(), 0, 0, 255, 0);
    SDL_RenderClear(mRenderer.get());
    SDL_RenderCopy(mRenderer.get(), mMarioTextTexture.get(), nullptr, &mMarioTextRect);
    SDL_RenderCopy(mRenderer.get(), mEnterTextTexture.get(), nullptr, &mEnterTextRect);
    SDL_RenderPresent(mRenderer.get());
}
как думаете норм так делать? или оставить там где был этот код?

Добавлено через 40 секунд
nonedark2008, а та я уже все класы переделал)))

Добавлено через 2 минуты
Теперь у меня так выглядат ифы
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if (state == State::StartMenuState)
        {
            
            RenderStartMenu renderStartMenu (renderer, marioTextSurface, marioTextFont, marioTextTexture, marioTextRect, enterTextSurface, enterTextFont, enterTextTexture, enterTextRect, windowWidth, windowHeight);
            
        }
        else if (state == State::PlayGameState)
        {
            
            RenderGamePlay renderGamePlay(renderer, marTextSurface, marTextFont, marTextTexture, marTextRect, timeTextSurface, timeTextFont, timeTextTexture, timeTextRect);
        }
        else if (state == State::EndMenuState)
        {
            
            RenderEndMenu renderEndMenu(renderer, gameOverTextSurface, gameOverTextFont, gameOverTextTexture, gameOverTextRect, windowWidth, windowHeight);
        }
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
26.07.2017, 01:34
Цитата Сообщение от dimaSlon Посмотреть сообщение
я вынес в деструктор код
Деструктор предназначен для удаления, делать там что-то другое не советую.
Сделай, скажем, у каждого класса метод Render - там и рисуй.
Да и объекты можно создать всего один раз, вынеси просто их из if.

Добавлено через 1 минуту
Прелесть объектов в том, что они могут хранить внутреннее состояние. У тебя же ничего такого нет, т.е. все классы можно заменить на самые обычные функции.
0
1 / 1 / 0
Регистрация: 23.06.2017
Сообщений: 153
26.07.2017, 22:19  [ТС]
nonedark2008,
Решил улутчить код: немного переделал. И снова выдает ошибки:
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "class std::unique_ptr<struct SDL_Surface,class std::function<void __cdecl(struct SDL_Surface *)> > __cdecl marioTextSurface(void)" (?marioTextSurface@@YA?AV?$unique_ptr@US DL_Surface@@V?$function@$$A6AXPAUSDL_Sur face@@@Z@std@@@std@@XZ) referenced in function "public: __thiscall RenderStartMenu::RenderStartMenu(class std::unique_ptr<struct SDL_Renderer,class std::function<void __cdecl(struct SDL_Renderer *)> > &,int,int)" (??0RenderStartMenu@@QAE@AAV?$unique_ptr @USDL_Renderer@@V?$function@$$A6AXPAUSDL _Renderer@@@Z@std@@@std@@HH@Z) Mario D:\Git\Mario\RenderStartMenu.obj 1


Severity Code Description Project File Line Suppression State
Error LNK1120 1 unresolved externals Mario D:\Git\Mario\Debug\Mario.exe 1

Код который переделал:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#pragma once
 
#include "Common.h"
 
class RenderStartMenu 
{
public:
    RenderStartMenu(SDLRendererPointer& renderer, const int windowWidth, const int windowHeight);
    void render();
 
private:
    SDLRendererPointer& mRenderer;
    SDL_Color mTextColor;
    TTFFontPointer mMarioTextFont;
    SDLSurfacePointer mMarioTextSurface;
    SDLTexturePointer mMarioTextTexture;
    SDL_Rect mMarioTextRect;
    
    TTFFontPointer mEnterTextFont;
    SDLSurfacePointer mEnterTextSurface;
    SDLTexturePointer mEnterTextTexture;
    SDL_Rect mEnterTextRect;
};
CPP
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "RenderStartMenu.h"
 
RenderStartMenu::RenderStartMenu(SDLRendererPointer& renderer, const int windowWidth, const int windowHeight)
    : mRenderer(renderer)
    , mTextColor({ 255, 255, 255, 255 })
    , mMarioTextFont(TTF_OpenFont("Resources/Fonts/Arial.TTF", 130), TTF_CloseFont)
    , mMarioTextSurface(TTF_RenderText_Solid(mMarioTextFont.get(), "Mario", mTextColor), SDL_FreeSurface)
    , mMarioTextTexture(SDL_CreateTextureFromSurface(renderer.get(), mMarioTextSurface.get()), SDL_DestroyTexture)
    , mMarioTextRect()
    , mEnterTextFont(TTF_OpenFont("Resources/Fonts/Arial.TTF", 30), TTF_CloseFont)
    , mEnterTextSurface(TTF_RenderText_Solid(mEnterTextFont.get(), "Press Space to enter", mTextColor), SDL_FreeSurface)
    , mEnterTextTexture(SDL_CreateTextureFromSurface(renderer.get(), mEnterTextSurface.get()), SDL_DestroyTexture)
    , mEnterTextRect()
{........}
Что я не так делаю?
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
27.07.2017, 01:42
Цитата Сообщение от dimaSlon Посмотреть сообщение
marioTextSurface
Кажись не находит реализацию функции с таким названием.
1
1 / 1 / 0
Регистрация: 23.06.2017
Сообщений: 153
21.08.2017, 12:02  [ТС]
Я снова переделал програму. Решил через state сделать.

C++
1
2
3
4
5
6
7
8
9
10
11
class GameState
{
public:
    virtual ~GameState() {}
 
    virtual void Enter() = 0;
    virtual void Exit() = 0;
    virtual void ProcessKeyboard(SDL_Keycode key) = 0;
    virtual void Update() = 0;
    virtual void Render() = 0;  
};
C++
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
 #include "Common.h"
#include "GameState.h"
 
class StartMenuStateListener
{
public:
    virtual ~StartMenuStateListener() {}
    virtual void OnGameStart() = 0;
};
 
class StartMenuState : public GameState
{
public:
    StartMenuState(StartMenuStateListener& listener, SDLRendererPointer renderer, const int windowWidth, const int windowHeight);
 
    void Enter() override;
    void Exit() override;
    void ProcessKeyboard(SDL_Keycode key) override;
    void Update() override;
    void Render() override;
 
private:
    StartMenuStateListener& mListener;
    SDLRendererPointer mRenderer;
 
    SDL_Color mTextColor;
    TTFFontPointer mMarioTextFont;
    SDLSurfacePointer mMarioTextSurface;
    SDLTexturePointer mMarioTextTexture;
    SDL_Rect mMarioTextRect;
    
    TTFFontPointer mEnterTextFont;
    SDLSurfacePointer mEnterTextSurface;
    SDLTexturePointer mEnterTextTexture;
    SDL_Rect mEnterTextRect;
};
Код первой странице
C++
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
#include "StartMenuState.h"
 
StartMenuState::StartMenuState(StartMenuStateListener& listener, SDLRendererPointer renderer, const int windowWidth, const int windowHeight)
    : mListener(listener)
    , mRenderer(renderer)
    , mTextColor({ 255, 255, 255, 255 })
    , mMarioTextFont(TTF_OpenFont("Resources/Fonts/Arial.TTF", 130), TTF_CloseFont)
    , mMarioTextSurface(TTF_RenderText_Solid(mMarioTextFont.get(), "Mario", mTextColor), SDL_FreeSurface)
    , mMarioTextTexture(SDL_CreateTextureFromSurface(renderer.get(), mMarioTextSurface.get()), SDL_DestroyTexture)
    , mMarioTextRect()
    , mEnterTextFont(TTF_OpenFont("Resources/Fonts/Arial.TTF", 30), TTF_CloseFont)
    , mEnterTextSurface(TTF_RenderText_Solid(mEnterTextFont.get(), "Press Space to enter", mTextColor), SDL_FreeSurface)
    , mEnterTextTexture(SDL_CreateTextureFromSurface(renderer.get(), mEnterTextSurface.get()), SDL_DestroyTexture)
    , mEnterTextRect()
{
    if (mMarioTextFont == nullptr)
    {
        SDL_Log("Unable to create font: %s", TTF_GetError());
    }
 
    if (mMarioTextSurface == nullptr)
    {
        SDL_Log("Unable to create surface: %s", TTF_GetError());
    }
 
    if (mMarioTextTexture == nullptr)
    {
        SDL_Log("Unable to create texture: %s", TTF_GetError());
    }
 
    SDL_QueryTexture(mMarioTextTexture.get(), nullptr, nullptr, &mMarioTextRect.w, &mMarioTextRect.h);
    mMarioTextRect.x = windowWidth / 2 - mMarioTextRect.w / 2;
    mMarioTextRect.y = windowHeight / 2 - mMarioTextRect.h / 2 - 50;
 
 
    if (mEnterTextFont == nullptr)
    {
        SDL_Log("Unable to create font: %s", TTF_GetError());
    }
 
    if (mEnterTextSurface == nullptr)
    {
        SDL_Log("Unable to create surface: %s", TTF_GetError());
    }
 
    if (mEnterTextTexture == nullptr)
    {
        SDL_Log("Unable to create texture: %s", TTF_GetError());
    }
 
    SDL_QueryTexture(mEnterTextTexture.get(), nullptr, nullptr, &mEnterTextRect.w, &mEnterTextRect.h);
    mEnterTextRect.x = windowWidth / 2 - mEnterTextRect.w / 2;
    mEnterTextRect.y = windowHeight / 2 - mEnterTextRect.h / 2 + mEnterTextRect.h;
    mListener.OnGameStart();
}
 
void StartMenuState::Enter()
{
}
 
void StartMenuState::Exit()
{
}
 
void StartMenuState::ProcessKeyboard(SDL_Keycode key)
{
    //if (key == SDLK_SPACE)
 
}
 
void StartMenuState::Update()
{
}
 
void StartMenuState::Render()
{
    SDL_SetRenderDrawColor(mRenderer.get(), 0, 0, 255, 0);
    SDL_RenderClear(mRenderer.get());
    SDL_RenderCopy(mRenderer.get(), mMarioTextTexture.get(), nullptr, &mMarioTextRect);
    SDL_RenderCopy(mRenderer.get(), mEnterTextTexture.get(), nullptr, &mEnterTextRect);
    SDL_RenderPresent(mRenderer.get());
}
C++
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
#include "StartMenuState.h"
 
StartMenuState::StartMenuState(StartMenuStateListener& listener, SDLRendererPointer renderer, const int windowWidth, const int windowHeight)
    : mListener(listener)
    , mRenderer(renderer)
    , mTextColor({ 255, 255, 255, 255 })
    , mMarioTextFont(TTF_OpenFont("Resources/Fonts/Arial.TTF", 130), TTF_CloseFont)
    , mMarioTextSurface(TTF_RenderText_Solid(mMarioTextFont.get(), "Mario", mTextColor), SDL_FreeSurface)
    , mMarioTextTexture(SDL_CreateTextureFromSurface(renderer.get(), mMarioTextSurface.get()), SDL_DestroyTexture)
    , mMarioTextRect()
    , mEnterTextFont(TTF_OpenFont("Resources/Fonts/Arial.TTF", 30), TTF_CloseFont)
    , mEnterTextSurface(TTF_RenderText_Solid(mEnterTextFont.get(), "Press Space to enter", mTextColor), SDL_FreeSurface)
    , mEnterTextTexture(SDL_CreateTextureFromSurface(renderer.get(), mEnterTextSurface.get()), SDL_DestroyTexture)
    , mEnterTextRect()
{
    if (mMarioTextFont == nullptr)
    {
        SDL_Log("Unable to create font: %s", TTF_GetError());
    }
 
    if (mMarioTextSurface == nullptr)
    {
        SDL_Log("Unable to create surface: %s", TTF_GetError());
    }
 
    if (mMarioTextTexture == nullptr)
    {
        SDL_Log("Unable to create texture: %s", TTF_GetError());
    }
 
    SDL_QueryTexture(mMarioTextTexture.get(), nullptr, nullptr, &mMarioTextRect.w, &mMarioTextRect.h);
    mMarioTextRect.x = windowWidth / 2 - mMarioTextRect.w / 2;
    mMarioTextRect.y = windowHeight / 2 - mMarioTextRect.h / 2 - 50;
 
 
    if (mEnterTextFont == nullptr)
    {
        SDL_Log("Unable to create font: %s", TTF_GetError());
    }
 
    if (mEnterTextSurface == nullptr)
    {
        SDL_Log("Unable to create surface: %s", TTF_GetError());
    }
 
    if (mEnterTextTexture == nullptr)
    {
        SDL_Log("Unable to create texture: %s", TTF_GetError());
    }
 
    SDL_QueryTexture(mEnterTextTexture.get(), nullptr, nullptr, &mEnterTextRect.w, &mEnterTextRect.h);
    mEnterTextRect.x = windowWidth / 2 - mEnterTextRect.w / 2;
    mEnterTextRect.y = windowHeight / 2 - mEnterTextRect.h / 2 + mEnterTextRect.h;
    mListener.OnGameStart();
}
 
void StartMenuState::Enter()
{
}
 
void StartMenuState::Exit()
{
}
 
void StartMenuState::ProcessKeyboard(SDL_Keycode key)
{
    //if (key == SDLK_SPACE)
 
}
 
void StartMenuState::Update()
{
}
 
void StartMenuState::Render()
{
    SDL_SetRenderDrawColor(mRenderer.get(), 0, 0, 255, 0);
    SDL_RenderClear(mRenderer.get());
    SDL_RenderCopy(mRenderer.get(), mMarioTextTexture.get(), nullptr, &mMarioTextRect);
    SDL_RenderCopy(mRenderer.get(), mEnterTextTexture.get(), nullptr, &mEnterTextRect);
    SDL_RenderPresent(mRenderer.get());
}
Создал клас MarioGame где все и буду делать:
C++
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
#pragma once
 
#include "Common.h"
#include "GameState.h"
#include "StartMenuState.h" 
#include "PlayGameState.h"
#include "EndMenuState.h"
 
class MarioGame : public StartMenuStateListener, public PlayGameStateListener, public EndMenuStateListener
{
public:
    MarioGame();
    ~MarioGame();
 
    void LaunchGame();
 
private:
    void EnterState(std::unique_ptr<GameState> newState);
 
    void OnGameStart() override;
    void OnLevelLose() override;
    void OnLevelComplete() override;
    void OnGameOver() override;
 
private:
    SDLRendererPointer mRenderer;
    SDLWindowPointer mWindow;
    std::unique_ptr<GameState> mCurrentState;
};
И в ней у меня есть функция где рисует и перерисовывает разные станы. Но ничего не рисуется. И нужна ваша помощь. Что я не так делаю?
C++
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
#include "MarioGame.h"
 
MarioGame::MarioGame()
    :mWindow(nullptr, SDL_DestroyWindow)
{
}
 
MarioGame::~MarioGame() 
{
}
 
void MarioGame::LaunchGame()
{
    while (true) 
    {
        const int windowWidth = 1280;
        const int windowHeight = 720;
 
        if (SDL_Init(SDL_INIT_VIDEO) != 0)
        {
            SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
            return;
        }
        SDLQuiter sdlQuiter(nullptr, [](void*) { SDL_Quit(); });
 
        if (TTF_Init() != 0)
        {
            SDL_Log("Unable to initialize TTF: %s", TTF_GetError());
            return;
        }
        TTFQuiter ttfQuiter(nullptr, [](void*) { TTF_Quit(); });
 
        mWindow.reset(SDL_CreateWindow(
            "Mario by Pavlo Naichuk",
            SDL_WINDOWPOS_UNDEFINED,
            SDL_WINDOWPOS_UNDEFINED,
            windowWidth,
            windowHeight,
            SDL_WINDOW_OPENGL
        ));
 
        if (mWindow == nullptr)
        {
            SDL_Log("Unable to created window: %s", SDL_GetError());
            return;
        }
 
        mRenderer.reset(SDL_CreateRenderer(mWindow.get(), -1,
            SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE), SDL_DestroyRenderer);
 
        if (mRenderer == nullptr)
        {
            SDL_Log("Failed to create renderer: %s", SDL_GetError());
            return;
        }
 
        SDL_Event event;
        for (bool runGame = true; runGame; )
        {
            if (SDL_PollEvent(&event))
            {
                switch (event.type)
                {
                case SDL_QUIT:
                {
                    runGame = false;
                    break;
                }
                case SDL_KEYDOWN:
                {
                    mCurrentState->ProcessKeyboard(event.key.keysym.sym);
                    break;
                }
                }
            }
            mCurrentState->Update();
            mCurrentState->Render();
        }
    }
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
21.08.2017, 12:02

Найти ошибку в программе
почему не работает, и как правильно сделать? var j, n : integer; begin readln(n); j := 0; while j &lt; n do ...

Найти ошибку в программе
Программа должна используя Дерево выводить список игроков сначала всех играющих в основном составе ниже играющих в резерве.... она же...

найти в программе ошибку
#make_COM# ; COM file is loaded at CS:0100h .286 Здесь выдаёт ошибку .model tiny .code org 100h start: mov...

Найти ошибку в программе
Ссылка на скрин с условием Ссылка удалена МОЕ РЕШЕНИЕ unit Unit1; interface

Найти ошибку в программе
program rsa; var p,q,i,n,e,novBukva,j: integer; f:boolean; a:string; c:char; g,d:longint; const b =...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
27
Ответ Создать тему
Новые блоги и статьи
10 сукцессия. Питон код войны грибов и растений
anaschu 27.06.2026
import numpy as np class PlantAgent: def __init__(self, name, strategy, initial_biomass): self. name = name self. strategy = strategy # "greedy" (широколиственные) или. . .
сукцессия 9. Математика подлости: как растения предали грибных друзей
anaschu 27.06.2026
Статья 2. Глобальная фосфорная война: эволюционно-экономические механизмы распределения биомов Земли Введение: Экологический рынок как игра с нулевой суммой Традиционная экология долгое время. . .
сукцессия 8. Как я спорил с ИИ, которые - агенты растений и ненавистники грибов!
anaschu 27.06.2026
Статья 1. Хроники грибного восстания: как Сократов диалог разрушил академические догмы ИИ Введение: Синдром «цифрового учебника» Современные большие языковые модели (LLM) обладают колоссальным. . .
Главный вопрос моделирования сукцессии
anaschu 27.06.2026
главный вопрос. Если эктомикориза лучше добывает недоступный фосфор. И ее масса максимальна из всех. А широколиственный лес тоже имеет самую крутую биомассу. То почему не возникло их симбиоза? Это. . .
сукцессия 6. Питон реализация энилоджиковской модели, картинка про Центральную часть будущей модели
anaschu 26.06.2026
Етить. ИИ мне на основе моего старого файла R создал вот эту вот хмерь на пайтоне. Это уже новая модель, модель сукцессии грибной. потоки фосфора, азота. Углерода. 5 видов организмов. Я даже. . .
Как замкнутый ядерный цикл решит проблему недостатки фосфора? Био миграция фосфора со дна океана
anaschu 26.06.2026
Биологический лифт: Концепция подъема фосфора со дна океана с помощью ЗЯТЦ Предлагаю на обсуждение альтернативу тяжелому промышленному бурению океанического дна. Вместо сложной инженерии мы можем. . .
сукцессия 5
anaschu 26.06.2026
ПЛАН РАЗРАБОТКИ математической модели сукцессии микоризных систем Переход AM → EcM (Endo + ErM) · Шумилов А. С. · ИФХиБПП РАН · Пущино · 2026 . . .
сукцессия 4
anaschu 25.06.2026
Более детализированный план разработки План доработки модели динамики микоризных симбиозов (EcM с гистерезисом) Цель: Реализовать логику переключения между эрикоидным (ErM) и эктомикоризным. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru