Demo: add a small easter egg when the 4x4 board of Selectable is filled + tweaked the demo.

This commit is contained in:
ocornut 2020-10-05 12:57:05 +02:00
parent 01cc666039
commit 014e5078a8

View File

@ -1088,27 +1088,34 @@ static void ShowDemoWindowWidgets()
} }
if (ImGui::TreeNode("Grid")) if (ImGui::TreeNode("Grid"))
{ {
static int selected[4 * 4] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
for (int i = 0; i < 4 * 4; i++)
{
ImGui::PushID(i);
if (ImGui::Selectable("Sailor", selected[i] != 0, 0, ImVec2(50, 50)))
{
// Toggle
selected[i] = !selected[i];
// Note: We _unnecessarily_ test for both x/y and i here only to silence some static analyzer. // Add in a bit of silly fun...
// The second part of each test is unnecessary. const float time = (float)ImGui::GetTime();
int x = i % 4; const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; // If all cells are selected...
int y = i / 4; if (winning_state)
if (x > 0) { selected[i - 1] ^= 1; } ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f)));
if (x < 3 && i < 15) { selected[i + 1] ^= 1; }
if (y > 0 && i > 3) { selected[i - 4] ^= 1; } for (int y = 0; y < 4; y++)
if (y < 3 && i < 12) { selected[i + 4] ^= 1; } for (int x = 0; x < 4; x++)
{
if (x > 0)
ImGui::SameLine();
ImGui::PushID(y * 4 + x);
if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(50, 50)))
{
// Toggle clicked cell + toggle neighbors
selected[y][x] ^= 1;
if (x > 0) { selected[y][x - 1] ^= 1; }
if (x < 3) { selected[y][x + 1] ^= 1; }
if (y > 0) { selected[y - 1][x] ^= 1; }
if (y < 3) { selected[y + 1][x] ^= 1; }
} }
if ((i % 4) < 3) ImGui::SameLine();
ImGui::PopID(); ImGui::PopID();
} }
if (winning_state)
ImGui::PopStyleVar();
ImGui::TreePop(); ImGui::TreePop();
} }
if (ImGui::TreeNode("Alignment")) if (ImGui::TreeNode("Alignment"))