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
|
#include <SFML/Graphics.hpp>
#include <vector>
#include <fstream>
#include <iostream>
std::vector<std::vector<sf::Vector2i> > loadMap( const char *filename );
void displayMap( std::vector<std::vector<sf::Vector2i> > map , const char *filename , sf::RenderWindow &window );
void generateRandomMap( const int ROWS , const int COLUMNS );
int main()
{
sf::RenderWindow window( sf::VideoMode( 640 , 480 , 32 ) , "Tile Map Loader" );
std::vector<std::vector<sf::Vector2i> > map;
map = loadMap( "map1.txt" );
displayMap( map , "tileset.png" , window );
while( window.isOpen() )
{
sf::Event event;
while( window.pollEvent(event) )
{
switch( event.type )
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
switch( event.key.code )
{
case sf::Keyboard::Key::L:
map = loadMap( "map1.txt" );
displayMap( map , "tileset.png" , window );
break;
case sf::Keyboard::Key::G:
generateRandomMap(15,20); //generate random 15 x 20 map
map = loadMap("map1.txt");
displayMap( map , "tileset.png" , window );
break;
}
break;
}
}
}
}
std::vector<std::vector<sf::Vector2i> > loadMap( const char *filename )
{
std::vector<std::vector<sf::Vector2i> >map;
std::vector<sf::Vector2i> tempMap;
sf::Vector2i tempCoord;
std::ifstream in( filename );
if( in.is_open() )
{
while( in.good() )
{
in >> tempCoord.x;
in >> tempCoord.y;
tempMap.push_back(tempCoord);
if( in.peek() == '\n' )
{
map.push_back(tempMap);
tempMap.clear();
}
}
}
in.close();
return( map );
}
void displayMap( std::vector<std::vector<sf::Vector2i> > map , const char *filename , sf::RenderWindow &window )
{
sf::Color background = sf::Color( 58 , 171 , 115 );
window.clear(background);
sf::Texture tileset;
tileset.loadFromFile(filename);
sf::Sprite tile(tileset);
const int SIZE = 32; //size of tile 32x32
for( int row = 0; row < map.size(); ++row )
{
for( int column = 0; column < map[row].size(); ++column )
{
if( map[row][column].x != -1 && map[row][column].y != -1 )
{
tile.setPosition(column * SIZE , row * SIZE );
tile.setTextureRect( sf::IntRect( map[row][column].x * SIZE , map[row][column].y * SIZE , SIZE , SIZE ) );
window.draw(tile);
}
}
}
window.display();
}
void generateRandomMap( const int ROWS , const int COLUMNS )
{
srand( (unsigned) time(NULL) );
std::ofstream out( "map1.txt" );
const short MAX_ROWS = 1;
const short MAX_COLUMNS = 4;
//tileset is a 1x4
for( int row = 0; row < ROWS; ++row )
{
for( int column = 0; column < COLUMNS; ++column )
{
out << ' ' << rand() % (MAX_COLUMNS+1) - 1 << ' ' << rand() % (MAX_ROWS+1) - 1;
}
out << '\n';
}
out.close();
}
|