Skip to content

Instantly share code, notes, and snippets.

@joseph-montanez
Created May 30, 2011 07:08
Show Gist options
  • Save joseph-montanez/998540 to your computer and use it in GitHub Desktop.
Save joseph-montanez/998540 to your computer and use it in GitHub Desktop.
Vector based tilemap
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <iostream>
#include <vector>
int main()
{
std::vector< std::vector<int> > map(4, std::vector<int>(4));
// Define the map
map[0][0] = 0;
map[0][1] = 1;
map[0][2] = 0;
map[0][3] = 0;
map[1][0] = 0;
map[1][1] = 0;
map[1][2] = 0;
map[1][3] = 0;
map[2][0] = 0;
map[2][1] = 0;
map[2][2] = 0;
map[2][3] = 0;
map[3][0] = 0;
map[3][1] = 0;
map[3][2] = 0;
map[3][3] = 1;
// Create the main rendering window
sf::RenderWindow App(sf::VideoMode(640, 480, 32), "SFML TileMap");
// Load the sprite image from a file
std::vector<sf::Image> images(2);
if (!images[0].LoadFromFile("grass.png")) {
return EXIT_FAILURE;
}
if (!images[1].LoadFromFile("water.png")) {
return EXIT_FAILURE;
}
// Create the sprite
std::vector<sf::Sprite> tiles(2);
tiles[0] = sf::Sprite(images[0]); // Grass
tiles[1] = sf::Sprite(images[1]); // Water
// Start game loop
while (App.IsOpened())
{
// Process events
sf::Event Event;
while (App.GetEvent(Event))
{
// Close window : exit
if (Event.Type == sf::Event::Closed)
App.Close();
}
// Get elapsed time
float ElapsedTime = App.GetFrameTime();
// Clear screen
App.Clear();
for (int x = 0; x < map.size (); x++) {
for (int y = 0; y < map[x].size (); y++) {
int tileId = map[x][y];
// Get the tile's image
const sf::Image* image = tiles[tileId].GetImage();
// Get the width and height of the image
int width = image->GetWidth();
int height = image->GetHeight();
// Adjust the offset by using the width
tiles[tileId].SetPosition(x * width, y * height);
// Draw the tile
App.Draw(tiles[tileId]);
}
}
// Display window contents on screen
App.Display();
sf::Sleep(1.0f / 60.0f);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment