Skip to content

Instantly share code, notes, and snippets.

@yknishidate
Last active March 3, 2022 09:38
Show Gist options
  • Save yknishidate/b64a232cd476e123da47a4f38bd1d8ab to your computer and use it in GitHub Desktop.
Save yknishidate/b64a232cd476e123da47a4f38bd1d8ab to your computer and use it in GitHub Desktop.
#include <iostream>
constexpr int WIDTH = 10;
constexpr int HEIGHT = 10;
class Terrain
{
public:
Terrain(int moveCost, bool isWater)
: m_moveCost(moveCost)
, m_isWater(isWater)
{}
int getMoveCost() const { return m_moveCost; }
bool isWater() const { return m_isWater; }
private:
int m_moveCost;
bool m_isWater;
};
class World
{
public:
World()
: m_grassTerrain(1, false)
, m_hillTerrain(3, false)
, m_riverTerrain(2, true)
{}
void generateTerrain()
{
for(int x = 0; x < WIDTH; x++){
for(int y = 0; y < HEIGHT; y++){
if(rand() % 10 == 0){
m_tiles[x][y] = &m_hillTerrain;
}else{
m_tiles[x][y] = &m_grassTerrain;
}
}
}
int x = rand() % WIDTH;
for(int y = 0; y < HEIGHT; y++){
m_tiles[x][y] = &m_riverTerrain;
}
}
const Terrain& getTile(int x, int y)
{
return *m_tiles[x][y];
}
private:
Terrain* m_tiles[WIDTH][HEIGHT];
Terrain m_grassTerrain;
Terrain m_hillTerrain;
Terrain m_riverTerrain;
};
int main()
{
World world;
world.generateTerrain();
for(int x = 0; x < WIDTH; x++){
for(int y = 0; y < HEIGHT; y++){
int moveCost = world.getTile(x, y).getMoveCost();
std::cout << moveCost << " ";
}
std::cout << std::endl;
}
}
@yknishidate
Copy link
Author

  • tilesにはポインタを持たせ、インスタンスを共有することでメモリを節約できる
  • WorldはTerrainの中身と結合していなくてGood
  • 今回はすべてのタイプのTerrainを最初に初期化しているが、実際は必要になった際に生成する方が一般的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment