Last active
April 5, 2018 00:08
-
-
Save shioken/fa2c3f5923170d86dd358b313d6ab244 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <M5Stack.h> | |
#define WIDTH 320 | |
#define HEIGHT 240 | |
#define BLOCK_SIZE 16 | |
#define UNIT_WIDTH ((WIDTH) / (BLOCK_SIZE)) | |
#define UNIT_HEIGHT ((HEIGHT) / (BLOCK_SIZE)) | |
#define UNIT_SIZE ((UNIT_WIDTH) * (UNIT_HEIGHT)) | |
#define GETX(i) ((i) % (UNIT_WIDTH)) | |
#define GETY(i) ((i) / (UNIT_WIDTH)) | |
#define GETINDEX(x, y) ((x) + (y) * UNIT_WIDTH) | |
int world[UNIT_SIZE][2]; | |
int current; | |
void setup() { | |
M5.begin(); | |
current = 0; | |
initWorld(); | |
} | |
void loop() { | |
if (M5.BtnC.wasPressed()) { | |
initWorld(); | |
} | |
if (M5.BtnA.wasPressed()) { | |
initGlider(); | |
} | |
nextWorld(); | |
updateWorld(); | |
M5.update(); | |
delay(33); | |
} | |
void initWorld() { | |
M5.Lcd.fillScreen(BLACK); | |
for (int i = 0; i < UNIT_SIZE; i++) { | |
world[i][current] = random(2); | |
if (world[i][current] > 0) { | |
int x = GETX(i); | |
int y = GETY(i); | |
M5.Lcd.fillRect(x * BLOCK_SIZE + 1, y * BLOCK_SIZE + 1, BLOCK_SIZE - 2, BLOCK_SIZE - 2, WHITE); | |
} | |
} | |
} | |
void initGlider() { | |
M5.Lcd.fillScreen(BLACK); | |
for (int i = 0; i < UNIT_SIZE; i++) { | |
world[i][current] = 0; | |
} | |
world[1][current] = 1; | |
world[2 + UNIT_WIDTH][current] = 1; | |
world[0 + UNIT_WIDTH * 2][current] = 1; | |
world[1 + UNIT_WIDTH * 2][current] = 1; | |
world[2 + UNIT_WIDTH * 2][current] = 1; | |
} | |
void nextWorld() { | |
for (int i = 0; i < UNIT_SIZE; i++) { | |
int x = GETX(i); | |
int y = GETY(i); | |
int count = 0; | |
for (int x1 = -1; x1 < 2; x1++) { | |
for (int y1 = -1; y1 < 2; y1++) { | |
if (x1 != 0 || y1 != 0) { | |
int index = GETINDEX((x + x1 + UNIT_WIDTH) % UNIT_WIDTH, (y + y1 + UNIT_HEIGHT) % UNIT_HEIGHT); | |
count += world[index][current]; | |
} | |
} | |
} | |
world[i][1 - current] = 0; | |
if (world[i][current] > 0) { | |
if (count == 2 || count == 3) { | |
world[i][1 - current] = 1; | |
} | |
} | |
else { | |
if (count == 3) { | |
world[i][1 - current] = 1; | |
} | |
} | |
} | |
current = 1 - current; | |
} | |
void updateWorld() { | |
for (int i = 0; i < UNIT_SIZE; i++) { | |
int x = GETX(i); | |
int y = GETY(i); | |
if (world[i][current] > 0) { | |
M5.Lcd.fillRect(x * BLOCK_SIZE + 1, y * BLOCK_SIZE + 1, BLOCK_SIZE - 2, BLOCK_SIZE - 2, WHITE); | |
} | |
else { | |
M5.Lcd.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE, BLACK); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment