Случайно сгенерированный уровень не отображается. Злые Обезьяны учебник

Привет, я сделал генератор уровней с помощью учебника 3D Buzz под названием Evil Monkeys. Я создал уровень, но не могу нарисовать его на экране.

Мой код:

Level.cpp

    #include "Level.h"
#include <stdlib.h>
#include "Sprite.h"
Level::Level(drawEngine *de, int w, int h)
{
    drawArea = de;

    width = w;
    height = h;

    gamer = 0;

    //create memory for our level
    level = new char *[width];

    for(int x = 0; x < width; x++)
    {
        level[x] = new char[height];
    }

    //create the level
    createLevel();

    drawArea->setMap(level);
}

Level::~Level()
{
    for(x = 0; x < width; x++)
        delete []level[x];

    delete [] level;
}

void Level::createLevel(void)
{
    for(int x = 0; x < width; x++)
    {
        for(int y = 0; y < height; y++)
        {
            int random = rand() % 100;

            if (y == 0 || y == height - 1 || x == 0 || x == width - 1)
            {
                level[x][y] = TILE_WALL;
            }
            else
            {
                if (random < 90 || (x < 3 && y < 3))
                    level[x][y] = TILE_EMPTY;
                else
                    level[x][y] = TILE_WALL;
            }
        }
    }
}


void Level::draw(void)
{
    // level to be drawn here
    drawArea->drawBackground();
}


Level.h

    #ifndef LEVEL_H
#define LEVEL_H

enum
{
    TILE_EMPTY,
    TILE_WALL
};
#include "drawEngine.h"
class Character;

class Level
{
public:
    Level(drawEngine *de, int width = 30, int height = 20);
    ~Level();
    int x;
    int y;

    void addPlayer(Character *p);
    void update(void);
    void draw(void);
    bool keyPress(char c);

protected:
    void createLevel(void);

private:
    int width;
    int height;
    char **level;

    Character *gamer;
    drawEngine *drawArea;

};

#endif

Game.cpp

    #include "Game.h"
#include <conio.h>
#include <iostream>
#include "drawEngine.h"
#include "Character.h"
#include <windows.h>
using namespace std;
//this will give ME 32 fps
#define GAME_SPEED 25.33
bool Runner::run()
{
    level = new Level(&drawArea, 30, 20);

    drawArea.createBackgroundTile(TILE_EMPTY, ' ');
    drawArea.createBackgroundTile(TILE_WALL, '+');

    drawArea.createSprite(0, '$');
    gamer = new Character(&drawArea, 0);

    level->draw();




    char key = ' ';

    startTime = timeGetTime();

    frameCount = 0;
    lastTime = 0;

    posX = 0;

    while (key != 'q')
    {
        while(!getInput(&key))
        {
            timerUpdate();
        }

        //gamer->keyPress(key);
        //cout << "Here's what you pressed: " << key << endl;
    }

    delete gamer;
    cout << frameCount / ((timeGetTime() - startTime) / 100) << " fps " << endl;
    cout << "Game Over" << endl;

    return true;
}

bool Runner::getInput(char *c)
{ 
    if (kbhit())
    {
        *c = getch();
        return true;
    }
}

void Runner::timerUpdate()
{
    double currentTime = timeGetTime() - lastTime;

    if (currentTime < GAME_SPEED)
        return;


    frameCount++;

    lastTime = timeGetTime();
}

game.h

#ifndef GAME_H
#define GAME_H
#include "drawEngine.h"
#include "Sprite.h"
#include "Character.h"
#include "level.h"


class Runner
{
public:
    bool run();



    Runner(){};
protected:
    bool getInput(char *c);

    void timerUpdate();
private:
    Level *level;
    Character* gamer;
    double frameCount;
    double startTime;
    double lastTime;

    int posX;



    drawEngine drawArea;
};

#endif

drawEngine.cpp

#include <iostream>
#include "drawEngine.h"
#include <windows.h>




using namespace std;
drawEngine::drawEngine(int index, int xSize, int ySize, int x, int y)
{
    screenWidth = x;
    screenHeight = y;

    map = 0;

    //set cursor visibility to false
    //cursorVisibility(false);


}

drawEngine::~drawEngine()
{
    cursorVisibility(true);
    //set cursor visibility to true
}

int drawEngine::createSprite(int index, char c)
{
    if (index >= 0 && index < 16)
    {
        spriteImage[index] = c;
    return index;
    }

    return -1;
}

void drawEngine::deleteSprite(int index)
{
    // in this implemantation we don't need it
}

void drawEngine::drawSprite(int index, int posX, int posY)
{
    //go to the correct location
    gotoxy (index, posX, posY);
    // draw the sprite

    cout << spriteImage[index];

    cursorVisibility(false);
}


void drawEngine::eraseSprite(int index, int posX, int posY)
{
    gotoxy (index, posX, posY);
    cout << ' '; 
}

void drawEngine::setMap(char **data)
{
    map = data;
}

void drawEngine::createBackgroundTile(int index, char c)
{
    if (index >= 0 && index < 16)
    {
        tileImage[index] = c;
    }

}

void drawEngine::drawBackground(void)
{
    if(map)
    {
        for(int y = 0; y < screenHeight; y++)
        {
            gotoxy(0,y, 0);

            for(int x = 0; x < screenWidth; x++)
                cout << tileImage[map[x][y]];

        }
    }
}

void drawEngine::gotoxy(int index, int x, int y)
{
    HANDLE output_handle;
    COORD pos;

    pos.X = x;
    pos.Y = y;

    output_handle = GetStdHandle(STD_OUTPUT_HANDLE);

    SetConsoleCursorPosition(output_handle, pos);
}

void drawEngine::cursorVisibility(bool visibility)
{
    HANDLE output_handle;
    CONSOLE_CURSOR_INFO cciInfo;

    cciInfo.dwSize = 1;
    cciInfo.bVisible = visibility;

    output_handle = GetStdHandle(STD_OUTPUT_HANDLE);

    SetConsoleCursorInfo(output_handle, &cciInfo);
}

drawEngine.h

#ifndef DRAWENGINE_H
#define DRAWENGINE_H
class drawEngine
{
public:
    drawEngine(int index, int xSize = 30, int ySize = 20, int x = 0, int y = 0);
    ~drawEngine();
    drawEngine(){};

    int createSprite(int index, char c);

    void deleteSprite(int index);
    void eraseSprite(int index, int posX, int posY);

    void createBackgroundTile(int index, char c);

    void drawSprite(int index, int posX, int posY);
    void drawBackground(void);

    void setMap(char **);
protected:
    char **map;
    int screenWidth, screenHeight;
    char spriteImage[16];
    char tileImage[16];
private:


    void gotoxy(int index, int x, int y);
    void cursorVisibility(bool visibility);

};

#endif

У меня также есть Sprite.cpp, Sprite.h, Character.h,Character.cpp и main.cpp, если они вам нужны

1 ответ

Хорошо, я сделал это через код и нашел одну проблему. Runner класс инкапсулирует drawEngine объект. У конструктора Runnerc'or по умолчанию drawEngine называется, который не устанавливает значения для sceenWidth а также screenHeight (или любой другой участник). К счастью, в режиме отладки они по умолчанию 0xcccccccc что отрицательно, так что вы drawBackground возвращается немедленно (Visual Studio 2010).
Вы должны изменить этот c'or (или даже удалить его) и правильно инициализировать двигатель в конструкторе бегуна, например:

class Runner {
public: 
    Runner() : drawArea(0, width, height, ?, ?){};
    [...]
};

Кроме того, x а также y члены используются в циклах в drawBackground, Вы должны использовать screenWidth а также screenWidthсоответственно Кстати, я не знаю, какие х и у должны быть drawEngine

ОБНОВЛЕНИЕ: координаты х и у на gotoxy вызывать drawBackground перепутаны, поэтому вы рисуете все на одной линии. Кстати: что это index используется для?

Другие вопросы по тегам