14
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Siv3D のコードを短くする

Last updated at Posted at 2017-12-05

Siv3D でコードを短く読みやすくするために知っておきたい Tips を紹介します。動作バージョンは OpenSiv3D v0.6.3 です。

1. RGB の省略

グレー

before.cpp
rect.draw(Color{ 127, 127, 127 });
after.cpp
rect.draw(Color{ 127 });
// または
rect.draw(ColorF{ 0.5 });

半透明

before.cpp
texture.draw(Color{ 255, 255, 255, 127 });
after.cpp
texture.draw(Alpha(127));
// または
texture.draw(AlphaF(0.5));

2. シーンと同じ大きさの Rect

before.cpp
const Rect rect{ 0, 0, Scene::Width(), Scene::Height() };
after.cpp
const Rect rect = Scene::Rect();

3. 正方形

before.cpp
const Rect rect{ 200, 300, 80, 80 };

const Rect rect2{ 0, 0, 80, 80 };
after.cpp
const Rect rect{ 200, 300, 80 };

const Rect rect2{ 80 };

4. 一回り大きい / 小さい Rect

before.cpp
const Rect rect2{ (rect.x - 10), (rect.y - 5), (rect.w + 20), (rect.h + 10) };
after.cpp
const Rect rect2 = rect.stretched(10, 5);

5. 指定した条件を満たす要素の削除

before.cpp
Array<Vec2> v;

for (auto it = v.begin(); it != v.end();)
{
	if (it->y < 0)
	{
		it = v.erase(it);
	}
	else
	{
		++it;
	}
}
after.cpp
Array<Vec2> v;
v.remove_if([](const Vec2& p) { return (p.y < 0); });

6. たくさんの数値の文字列化

before.cpp
font(U"ステージ ", stage, U" 得点: ", score, U" タイム: ", time, U" 評価: ", result).draw(); 
after.cpp
font(U"ステージ {} 得点: {} タイム: {} 評価: {}"_fmt(stage, score, time, result)).draw(); 

7. ストップウォッチを即座にスタート

before.cpp
Stopwatch stopwatch;

stopwatch.start();
after.cpp
Stopwatch stopwatch{ StartImmediately::Yes };

8. emplace_back()

before.cpp
Array<Vec3> v;
v.push_back(Vec3{ 0.1, 0.2, 0.3 });
after.cpp
Array<Vec3> v;
v.emplace_back(0.1, 0.2, 0.3);

9. 画像の全ピクセルへのアクセス

before.cpp
for (int32 y = 0; y < image.height(); ++y)
{
	for (int32 x = 0; x < image.width(); ++x)
	{
		image[y][x].r = 0;
	}
}
after.cpp
for (auto& pixel : image)
{
	pixel.r = 0;
}

10. 時刻や日付の文字列化

before.cpp
const Date today = Date::Today();

font(U"{}月{}日"_fmt(today.month, today.day)).draw();
after.cpp
const Date today = Date::Today();

font(today.format(U"M月d日")).draw();

11. 確率

before.cpp
if (Random(1.0) < 0.33)
{

}
after.cpp
if (RandomBool(0.33))
{

}

12. draw の戻り値

before.cpp
const Rect rect{ 200, 200, 300, 100 };

rect.draw(Palette::Orange);

rect.drawFrame(2, 0, Palette::White);
after.cpp
const Rect rect{ 200, 200, 300, 100 };

rect.draw(Palette::Orange).drawFrame(2, 0, Palette::White);

Siv3D でこのコードをもっと短く書きたい!というリクエストは、OpenSiv3D の GitHub issue や Siv3D Slack で受け付けています。

14
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?