1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Arduino Unoと8×8 LEDで、ぷよぷよを自動プレイする卓上ディスプレイ

1
Last updated at Posted at 2026-11-28

IMG_3732.jpeg

はじめに

5mm角のフルカラーLEDが8×8個並んだ基板を使い、ぷよぷよ風の落ち物ゲームを自動プレイする卓上ディスプレイを制作しました。

人間による操作は不要です。Arduino Unoが自動的にぷよの配置を考え、積み上げ、連鎖を発生させます。ゲームオーバーになっても自動的に再スタートするため、スクリーンセーバーのように眺めて楽しめます。

今回のポイントは、Arduino Unoの限られた計算能力とメモリで、2手先読みと大連鎖を育てるための評価を行いながら、LEDアニメーションをできるだけ止めないことです。

使用機材と配線

  • Arduino Uno(ATmega328P、16MHz、SRAM 2KB)
  • WS2812B互換のフルカラーLEDマトリクス(8×8、64個)
  • USB電源
  • Arduino IDE
  • Adafruit NeoPixelライブラリ

Arduino IDEのライブラリマネージャーから Adafruit NeoPixel をインストールします。

LED基板 接続先
DIN Arduino D7(330Ω程度の直列抵抗を推奨)
GND Arduino GNDと電源GND
5V 安定した5V電源

今回の基板は各行が同じ方向に並ぶ直線配列です。ジグザグ配列の場合は SERPENTINE を true に変更します。乱数初期化用のA0は未接続にします。

64個のLEDを最大輝度で白色点灯すると、従来型WS2812Bでは最大約3.84Aに達する可能性があります。Arduinoの5V端子やPCのUSBポートから無条件に供給できる電流ではありません。本コードは通常輝度10、消去時最大40に抑えていますが、安全性は電源・基板・配線の定格と実測電流で確認してください。必要に応じてLEDを独立した5V電源から給電し、ArduinoとGNDを共通にしてください。独立給電時はArduino側の5Vと外部電源の5Vを不用意に直結しないでください。

ゲームの仕様

項目 設定
盤面 8×8
色 赤・緑・青・黄・紫(3〜5色に変更可能)
操作 完全自動
消去条件 上下左右に同色が4個以上連結
AI 2手先読み+潜在連鎖評価
通常輝度 10 / 255
消去演出 元の色のまま輝度5〜40で3回明滅し、フェードアウト
全消し 虹色アニメーション
ゲームオーバー 上から順に消灯し、自動再スタート

一般的なぷよぷよと異なり、出現位置は固定せず、任意の列に2個組を落とします。横置きで片方が浮いた場合は、着地後に重力で下へ詰めます。全配置が不可能になるまでプレイを継続します。

AIの仕組み

2手先読み

現在の2個組について、8列×4方向の最大32候補を調べます。範囲外の配置を除けば最大30候補です。各候補について着地・消去・重力・連鎖を仮想盤面上で実行し、さらに次の2個組についても同様に探索します。

盤面評価では、同色の隣接、1マス離れた同色、斜めの同色を加点し、高い積み上がりや列の高低差を減点します。適度にぷよを残すことにも加点します。

連鎖の消去評価は次の式です。通常のゲームの得点ではなく、AI内部の評価値です。

$$ S = 35 \sum_{k=1}^{n} m_k k^2 $$

ここで、$n$ は連鎖数、$m_k$ は第 $k$ 連鎖で消えるぷよの個数です。全消しには250点を加えます。

潜在連鎖評価

2手先読みだけでは、すぐに消去できる配置が優先され、大連鎖の構造を育てにくいことがあります。

そこで、1手目の処理後の盤面に、各列・各色のぷよを仮想的に1個だけ追加し、何連鎖発生するかを調べます。最大潜在連鎖数を $L$、2連鎖以上を発火できる候補数を $T$ とすると、$L \geq 2$ の場合に以下を加点します。

$$ P = 100L^2 + 20T $$

1連鎖以下なら加点しません。実際の配置評価は概ね次の形です。

$$ F = S_1/4 + E_1/3 + \max(S_2+E_2) + P $$

$S_1,S_2$ は連鎖消去評価、$E_1,E_2$ は盤面評価です(コードでは整数除算)。次の配置が不可能な場合には大きく減点し、最後に0〜5の乱数を加えます。

潜在連鎖を温存する評価により、すぐ消すのではなく、将来の発火を狙って積む動きが生まれます。ただし最適な大連鎖や永続プレイを保証するアルゴリズムではありません。

Arduino Unoでの高速化

1. アニメーション中に次の手を探索する

自動プレイでは人間の割り込み操作がないので、現在のぷよが着地し、すべての連鎖が終了した盤面を事前に計算できます。

その予測盤面を使って、現在のぷよが落下している間から次の手の探索を開始します。通常の delay() の代わりに smartDelay() を使い、待機時間内に探索を1候補ずつ進めます。落下、消去演出、全消し演出の待機時間を利用できます。

void smartDelay(unsigned long ms) {
  unsigned long start = millis();
  while (millis() - start < ms) {
    if (ai.active) searchStep();
    else delay(1);
  }
}

マルチスレッドではなく、シングルコアでの協調的な時分割処理です。アニメーション終了時に探索が未完了なら残りを実行します。1探索ステップが長い場合には表示間隔が延びることもあります。

2. 重力処理を一括化する

LED表示では1マスずつ落下させますが、AIの仮想盤面では途中経過は不要です。各列を下から走査して非空セルを下端に詰め、重力を一度に処理します。消去後に何度も盤面全体を走査する必要がなくなります。

3. 盤面を1次元配列にして連結成分を探索する

盤面は64バイトの uint8_t 配列です。幅が8なので、座標とインデックスをビット演算で変換できます。

p = (y << 3) | x;
x = p & 7;
y = p >> 3;

幅優先探索(BFS)で同色の連結成分を調べます。キューと訪問済み配列を固定長の共有作業領域とし、動的メモリ確保や再帰を避けています。表示用の消去マスクはAI用のマスクと分離しているため、発光演出中にAIが探索しても消去対象は保持されます。

4. 発火しない候補を除外する

潜在連鎖の探索では、5色なら8列×5色の最大40候補を調べます。しかし、安定した盤面に1個だけ追加した場合、そのぷよを含む同色連結成分が4個未満なら消去は始まりません。

まず隣接する同色があるかを確認し、次に追加したぷよを起点とするBFSで連結数を調べます。4個以上の場合だけ、盤面全体の連鎖シミュレーションを行います。安定盤面という前提のもとで、発火可能な候補を落とさずに計算を省略できます。

5. 同色ペアの重複配置を省く

2個が同色なら上下を交換しても結果は同じです。横方向も、基準列をずらせば左右反転した同じ配置が得られます。そこで同色ペアでは2方向だけを調べます。最大30候補が15候補になり、2手先探索でも重複を削減できます。同点時の乱数消費順は変わるため、プレイの完全な再現性は最適化前と異なります。

6. RAMと浮動小数点演算の節約

Arduino UnoのSRAMは2KBしかありません。ログ文字列は F()、発光曲線の25サンプルは PROGMEM を使ってフラッシュメモリに置きます。発光時に毎回 sin() を計算する代わりにテーブル参照と整数演算で輝度を求めます。

消去アニメーションと乱数

消去対象だけを元の色のまま輝度5〜40で3回明滅させます。白色への変更は行いません。25サンプルの発光曲線を使用し、1サンプルあたりの待機時間は5msです。3周期と6サンプルのフェードアウトで、待機時間の合計は405msです。実際の演出時間にはLED転送や描画の時間が加わります。

起動時は未接続のA0から32回アナログ値を読み、下位1ビットを集めた値に micros() を混ぜて乱数シードを作ります。電源投入ごとの変化を得るための簡易的な方法であり、毎回異なる乱数シードや暗号学的な乱数品質を保証するものではありません。ゲームオーバー時は乱数列を継続します。

動作結果

4色設定での実機計測では、68手時点で最大8連鎖を確認できました。少なくとも8×4=32個のぷよが一連の連鎖で消えたことになります。

高速化後の探索ログの抜粋です。

Game: 1
Turns: 68
Max chain: 8
All clear: 0
1 chain: 5
2 chain: 0
3 chain: 0
4 chain: 1
5 chain: 1
6 chain: 0
7 chain: 0
8 chain: 1
AI計算時間(ms) アニメーション終了後の追加待機(ms)
389 0
629 0
678 0
806 35
447 0
484 0

6件のうち5件はアニメーション中に探索を完了しました。高速化前には密な盤面で3335msのAI計算と2654msの追加待機が観測されましたが、高速化後の上記6件では追加待機は最大35msでした。異なる盤面での測定なので厳密な速度比較ではありません。

ここで紹介する最終コードは5色設定です。上記の8連鎖および時間計測は4色設定で得た結果であり、5色設定で同じ性能・連鎖数を保証するものではありません。

全コード(V5.2)

以下をArduino IDEに貼り付けて書き込みます。シリアルモニタは115200bpsです。

PUYO_AUTO_V5_2.ino
#include <Adafruit_NeoPixel.h>
#include <avr/pgmspace.h>

// ========================================
// 設定
// ========================================

#define LED_PIN 7
#define LED_COUNT 64

#define W 8
#define H 8

#define SERPENTINE false
#define FLIP_X false
#define FLIP_Y false

#define COLOR_COUNT 5

// 輝度・点滅設定
#define BRIGHTNESS 10
#define FLASH_MIN_BRIGHTNESS 5
#define FLASH_BRIGHTNESS 40
#define FLASH_COUNT 3

// アニメーション速度
#define FALL_DELAY 100
#define GRAVITY_DELAY 90
#define TURN_DELAY 0
#define PULSE_DELAY 5 // 点滅速度

// AI設定
#define POTENTIAL_WEIGHT 100

// 乱数初期化用アナログ端子
#define RANDOM_PIN A0

// ========================================
// LED・盤面
// ========================================

Adafruit_NeoPixel pixels(
  LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800
);

typedef uint8_t Board[64];

Board field;

const int8_t dx[4] = {0, 1, 0, -1};
const int8_t dy[4] = {-1, 0, 1, 0};

const uint8_t rgb[6][3] = {
  {  0,   0,   0}, // 消灯
  {255,   0,   0}, // 赤
  {  0, 255,   0}, // 緑
  {  0,   0, 255}, // 青
  {255, 200,   0}, // 黄
  {200,   0, 255}  // 紫
};

// 発光曲線
const uint8_t pulseTable[25] PROGMEM = {
    0,  33,  66,  98, 128,
  155, 180, 202, 221, 236,
  246, 253, 255, 253, 246,
  236, 221, 202, 180, 155,
  128,  98,  66,  33,   0
};

// 探索用作業メモリ
uint8_t visited[64];
uint8_t queueBuffer[64];
uint8_t simMarked[64];

int current1, current2;
int next1, next2;

// 統計
uint8_t maxChainRecord = 0;

unsigned long totalTurns = 0;
unsigned long gameCount = 1;
unsigned long allClearCount = 0;
unsigned long chainCount[17] = {};

// ========================================
// AI探索状態
// ========================================

struct SearchState {

  Board base;
  Board temp1;

  uint8_t c1, c2;
  uint8_t n1, n2;

  uint8_t candidate;
  uint8_t nextCandidate;
  uint8_t potentialCandidate;

  uint8_t maxPotentialChain;
  uint8_t triggerCount;

  long score1;
  long bestNext;
  long bestScore;

  uint8_t bestX;
  uint8_t bestRot;

  uint8_t phase;

  bool active;
  bool found;
  bool nextFound;

  unsigned long cpuMicros;
  unsigned long startMillis;
  unsigned long elapsedMillis;
};

SearchState ai;

void searchStep();
void smartDelay(unsigned long ms);

// ========================================
// V5.2:アナログノイズによる乱数初期化
// ========================================

void initializeRandom() {

  pinMode(RANDOM_PIN, INPUT);
  digitalWrite(RANDOM_PIN, LOW);

  // ADCを安定させるための空読み
  analogRead(RANDOM_PIN);

  uint32_t seed = 0;

  // アナログ入力の下位ビットを収集
  for (uint8_t i = 0; i < 32; i++) {

    seed = (seed << 1)
         | (analogRead(RANDOM_PIN) & 1);

    delay(1);
  }

  // 起動後の経過時間も混ぜる
  seed ^= micros();

  // randomSeed(0)を避ける
  if (seed == 0)
    seed = 1;

  randomSeed(seed);

  Serial.print(F("Random seed: "));
  Serial.println(seed);
}

// ========================================
// LED描画
// ========================================

uint8_t ledIndex(uint8_t x, uint8_t y) {

  if (FLIP_X) x = 7 - x;
  if (FLIP_Y) y = 7 - y;

  if (SERPENTINE && (y & 1))
    x = 7 - x;

  return (y << 3) | x;
}

void drawPuyo(
  int8_t x, int8_t y,
  uint8_t c, uint8_t brightness
) {

  if (x < 0 || x >= 8 ||
      y < 0 || y >= 8)
    return;

  pixels.setPixelColor(
    ledIndex(x, y),
    (uint16_t)rgb[c][0] * brightness / 255,
    (uint16_t)rgb[c][1] * brightness / 255,
    (uint16_t)rgb[c][2] * brightness / 255
  );
}

void drawField() {

  pixels.clear();

  for (uint8_t p = 0; p < 64; p++) {

    if (field[p]) {

      drawPuyo(
        p & 7,
        p >> 3,
        field[p],
        BRIGHTNESS
      );
    }
  }
}

// ========================================
// 衝突判定
// ========================================

bool emptyCell(
  const uint8_t *b,
  int8_t x, int8_t y
) {

  if (x < 0 || x >= 8 || y >= 8)
    return false;

  if (y < 0)
    return true;

  return b[(y << 3) | x] == 0;
}

bool canMove(
  const uint8_t *b,
  int8_t x, int8_t y,
  uint8_t rot
) {

  return emptyCell(b, x, y) &&
         emptyCell(
           b,
           x + dx[rot],
           y + dy[rot]
         );
}

int8_t landingY(
  const uint8_t *b,
  int8_t x, uint8_t rot
) {

  int8_t y = -2;

  if (!canMove(b, x, y, rot))
    return -99;

  while (canMove(b, x, y + 1, rot))
    y++;

  if (y < 0 || y + dy[rot] < 0)
    return -99;

  return y;
}

// ========================================
// 重力:表示用
// ========================================

bool gravity(uint8_t *b) {

  bool moved = false;

  for (int8_t p = 55; p >= 0; p--) {

    if (b[p] && !b[p + 8]) {

      b[p + 8] = b[p];
      b[p] = 0;

      moved = true;
    }
  }

  return moved;
}

// ========================================
// 高速重力処理
// シミュレーション専用
// ========================================

void compactGravity(uint8_t *b) {

  for (uint8_t x = 0; x < 8; x++) {

    int8_t dst = 56 + x;

    for (int8_t src = 56 + x;
         src >= 0; src -= 8) {

      if (b[src]) {

        uint8_t c = b[src];

        b[src] = 0;
        b[dst] = c;

        dst -= 8;
      }
    }

    while (dst >= 0) {

      b[dst] = 0;
      dst -= 8;
    }
  }
}

// ========================================
// 高速連結成分探索
// ========================================

inline void enqueueCell(
  const uint8_t *b,
  uint8_t p,
  uint8_t color,
  uint8_t &tail
) {

  if (!visited[p] && b[p] == color) {

    visited[p] = 1;
    queueBuffer[tail++] = p;
  }
}

uint8_t floodFill(
  const uint8_t *b,
  uint8_t start
) {

  uint8_t color = b[start];

  uint8_t head = 0;
  uint8_t tail = 1;

  queueBuffer[0] = start;
  visited[start] = 1;

  while (head < tail) {

    uint8_t p = queueBuffer[head++];

    if ((p & 7) != 0)
      enqueueCell(b, p - 1, color, tail);

    if ((p & 7) != 7)
      enqueueCell(b, p + 1, color, tail);

    if (p >= 8)
      enqueueCell(b, p - 8, color, tail);

    if (p < 56)
      enqueueCell(b, p + 8, color, tail);
  }

  return tail;
}

// ========================================
// 同色4個以上のグループを検出
// ========================================

uint8_t findMatches(
  const uint8_t *b,
  uint8_t *marked
) {

  memset(visited, 0, 64);
  memset(marked, 0, 64);

  uint8_t total = 0;

  for (uint8_t p = 0; p < 64; p++) {

    if (!b[p] || visited[p])
      continue;

    uint8_t count = floodFill(b, p);

    if (count >= 4) {

      total += count;

      for (uint8_t i = 0; i < count; i++)
        marked[queueBuffer[i]] = 1;
    }
  }

  return total;
}

// ========================================
// 発火可能性の高速判定
// ========================================

bool canTrigger(
  const uint8_t *b,
  uint8_t p
) {

  uint8_t c = b[p];

  bool neighbor = false;

  if ((p & 7) != 0 && b[p - 1] == c)
    neighbor = true;

  if ((p & 7) != 7 && b[p + 1] == c)
    neighbor = true;

  if (p >= 8 && b[p - 8] == c)
    neighbor = true;

  if (p < 56 && b[p + 8] == c)
    neighbor = true;

  if (!neighbor)
    return false;

  memset(visited, 0, 64);

  return floodFill(b, p) >= 4;
}

// ========================================
// 全消し判定
// ========================================

bool isEmpty(const uint8_t *b) {

  for (uint8_t p = 0; p < 64; p++)
    if (b[p])
      return false;

  return true;
}

// ========================================
// 高速シミュレーション用連鎖処理
// ========================================

long resolveFast(uint8_t *b) {

  uint8_t chain = 0;
  long score = 0;

  compactGravity(b);

  while (true) {

    uint8_t count = findMatches(b, simMarked);

    if (!count)
      break;

    chain++;

    score += (long)count *
             chain * chain * 35;

    for (uint8_t p = 0; p < 64; p++) {

      if (simMarked[p])
        b[p] = 0;
    }

    compactGravity(b);
  }

  if (chain && isEmpty(b))
    score += 250;

  return score;
}

// ========================================
// 仮想盤面の連鎖数計測
// ========================================

uint8_t countChains(uint8_t *b) {

  uint8_t chain = 0;

  compactGravity(b);

  while (true) {

    if (!findMatches(b, simMarked))
      break;

    chain++;

    for (uint8_t p = 0; p < 64; p++) {

      if (simMarked[p])
        b[p] = 0;
    }

    compactGravity(b);
  }

  return chain;
}

// ========================================
// AI盤面評価
// ========================================

long evaluate(const uint8_t *b) {

  int16_t score = 0;

  uint8_t heights[8] = {};
  uint8_t maxHeight = 0;
  uint8_t occupied = 0;

  for (uint8_t x = 0; x < 8; x++) {

    for (uint8_t y = 0; y < 8; y++) {

      uint8_t p = (y << 3) | x;
      uint8_t c = b[p];

      if (!c)
        continue;

      occupied++;

      if (8 - y > heights[x])
        heights[x] = 8 - y;

      if (x < 7 && b[p + 1] == c)
        score += 22;

      if (y < 7 && b[p + 8] == c)
        score += 22;

      if (x < 6 && b[p + 2] == c)
        score += 9;

      if (y < 6 && b[p + 16] == c)
        score += 9;

      if (x < 7 && y < 7 &&
          b[p + 9] == c)
        score += 5;

      if (x > 0 && y < 7 &&
          b[p + 7] == c)
        score += 5;
    }

    if (heights[x] > maxHeight)
      maxHeight = heights[x];

    score -= heights[x] * heights[x] * 2;
  }

  for (uint8_t x = 0; x < 7; x++) {

    int8_t diff =
      heights[x] - heights[x + 1];

    score -= diff * diff * 3;
  }

  if (occupied <= 24)
    score += occupied * 6;
  else
    score += 144 - (occupied - 24) * 8;

  if (maxHeight >= 6)
    score -= (maxHeight - 5) * 100;

  return score;
}

// ========================================
// 重複配置の除外
// ========================================

bool validCandidate(
  uint8_t c1, uint8_t c2,
  uint8_t x, uint8_t rot
) {

  if (rot == 1 && x == 7)
    return false;

  if (rot == 3 && x == 0)
    return false;

  if (c1 == c2 && rot >= 2)
    return false;

  return true;
}

// ========================================
// 配置シミュレーション
// ========================================

bool simulateMove(
  uint8_t *b,
  uint8_t c1, uint8_t c2,
  uint8_t x, uint8_t rot,
  long &score
) {

  int8_t y = landingY(b, x, rot);

  if (y == -99)
    return false;

  b[(y << 3) | x] = c1;

  uint8_t x2 = x + dx[rot];
  uint8_t y2 = y + dy[rot];

  b[(y2 << 3) | x2] = c2;

  score = resolveFast(b);

  return true;
}

// ========================================
// AI探索開始
// ========================================

void startSearch(
  const uint8_t *b,
  uint8_t c1, uint8_t c2,
  uint8_t n1, uint8_t n2
) {

  memcpy(ai.base, b, 64);

  ai.c1 = c1;
  ai.c2 = c2;

  ai.n1 = n1;
  ai.n2 = n2;

  ai.candidate = 0;
  ai.nextCandidate = 0;
  ai.potentialCandidate = 0;

  ai.bestScore = -1000000L;
  ai.bestNext = -1000000L;

  ai.bestX = 0;
  ai.bestRot = 0;

  ai.phase = 0;

  ai.active = true;
  ai.found = false;
  ai.nextFound = false;

  ai.cpuMicros = 0;
  ai.startMillis = millis();
  ai.elapsedMillis = 0;
}

// ========================================
// 分割AI探索
// ========================================

void searchStepInternal() {

  if (!ai.active)
    return;

  if (ai.candidate >= 32) {

    ai.active = false;

    ai.elapsedMillis =
      millis() - ai.startMillis;

    return;
  }

  uint8_t x = ai.candidate >> 2;
  uint8_t rot = ai.candidate & 3;

  // ------------------------------------
  // 1手目の配置
  // ------------------------------------

  if (ai.phase == 0) {

    if (!validCandidate(
      ai.c1, ai.c2, x, rot
    )) {

      ai.candidate++;
      return;
    }

    memcpy(ai.temp1, ai.base, 64);

    if (!simulateMove(
      ai.temp1,
      ai.c1, ai.c2,
      x, rot,
      ai.score1
    )) {

      ai.candidate++;
      return;
    }

    ai.nextCandidate = 0;

    ai.bestNext = -1000000L;
    ai.nextFound = false;

    ai.phase = 1;

    return;
  }

  // ------------------------------------
  // 2手目の探索
  // ------------------------------------

  if (ai.phase == 1) {

    if (ai.nextCandidate >= 32) {

      ai.potentialCandidate = 0;
      ai.maxPotentialChain = 0;
      ai.triggerCount = 0;

      ai.phase = 2;

      return;
    }

    uint8_t nx = ai.nextCandidate >> 2;
    uint8_t nr = ai.nextCandidate & 3;

    ai.nextCandidate++;

    if (!validCandidate(
      ai.n1, ai.n2, nx, nr
    ))
      return;

    Board temp;

    memcpy(temp, ai.temp1, 64);

    long score2;

    if (simulateMove(
      temp,
      ai.n1, ai.n2,
      nx, nr,
      score2
    )) {

      long s = score2 + evaluate(temp);

      if (s > ai.bestNext) {

        ai.bestNext = s;
        ai.nextFound = true;
      }
    }

    return;
  }

  // ------------------------------------
  // 潜在連鎖の探索
  // ------------------------------------

  if (ai.phase == 2) {

    if (ai.potentialCandidate >=
        8 * COLOR_COUNT) {

      ai.phase = 3;
      return;
    }

    uint8_t px =
      ai.potentialCandidate / COLOR_COUNT;

    uint8_t pc =
      ai.potentialCandidate % COLOR_COUNT + 1;

    ai.potentialCandidate++;

    int8_t p = 56 + px;

    while (p >= 0 && ai.temp1[p])
      p -= 8;

    if (p < 0)
      return;

    Board temp;

    memcpy(temp, ai.temp1, 64);

    temp[p] = pc;

    if (!canTrigger(temp, p))
      return;

    uint8_t chain = countChains(temp);

    if (chain > ai.maxPotentialChain)
      ai.maxPotentialChain = chain;

    if (chain >= 2)
      ai.triggerCount++;

    return;
  }

  // ------------------------------------
  // 最終評価
  // ------------------------------------

  if (ai.phase == 3) {

    long potential = 0;

    if (ai.maxPotentialChain >= 2) {

      potential =
        (long)ai.maxPotentialChain *
        ai.maxPotentialChain *
        POTENTIAL_WEIGHT +
        ai.triggerCount * 20;
    }

    long finalScore =
      ai.score1 / 4 +
      evaluate(ai.temp1) / 3 +
      ai.bestNext +
      potential;

    if (!ai.nextFound)
      finalScore = -500000L + ai.score1;

    finalScore += random(0, 6);

    if (finalScore > ai.bestScore) {

      ai.bestScore = finalScore;

      ai.bestX = x;
      ai.bestRot = rot;

      ai.found = true;
    }

    ai.candidate++;
    ai.phase = 0;
  }
}

// ========================================
// AI処理時間計測
// ========================================

void searchStep() {

  if (!ai.active)
    return;

  unsigned long t = micros();

  searchStepInternal();

  ai.cpuMicros += micros() - t;
}

// ========================================
// アニメーション中に探索
// ========================================

void smartDelay(unsigned long ms) {

  unsigned long start = millis();

  while (millis() - start < ms) {

    if (ai.active)
      searchStep();
    else
      delay(1);
  }
}

unsigned long completeSearch() {

  unsigned long start = millis();

  while (ai.active)
    searchStep();

  return millis() - start;
}

// ========================================
// 探索時間表示
// ========================================

void printSearchTime(
  unsigned long waitTime
) {

  Serial.print(F("AI CPU: "));
  Serial.print(ai.cpuMicros / 1000);
  Serial.print(F(" ms"));

  Serial.print(F(" / Elapsed: "));
  Serial.print(ai.elapsedMillis);
  Serial.print(F(" ms"));

  Serial.print(F(" / Extra wait: "));
  Serial.print(waitTime);
  Serial.println(F(" ms"));
}

// ========================================
// 連鎖発光
// 点滅回数固定・元の色を維持
// ========================================

void chainEffect(
  const uint8_t *marked,
  uint8_t chain
) {

  for (uint8_t k = 0; k < FLASH_COUNT; k++) {

    for (uint8_t t = 0; t <= 24; t++) {

      uint8_t s =
        pgm_read_byte(&pulseTable[t]);

      uint8_t v =
        FLASH_MIN_BRIGHTNESS +
        (uint16_t)(
          FLASH_BRIGHTNESS -
          FLASH_MIN_BRIGHTNESS
        ) * s / 255;

      drawField();

      for (uint8_t p = 0; p < 64; p++) {

        if (marked[p]) {

          drawPuyo(
            p & 7,
            p >> 3,
            field[p],
            v
          );
        }
      }

      pixels.show();

      smartDelay(PULSE_DELAY);
    }
  }

  // 最後にフェードアウト
  for (int16_t v = FLASH_MIN_BRIGHTNESS;
       v >= 0; v--) {

    drawField();

    for (uint8_t p = 0; p < 64; p++) {

      if (marked[p]) {

        drawPuyo(
          p & 7,
          p >> 3,
          field[p],
          v
        );
      }
    }

    pixels.show();

    smartDelay(PULSE_DELAY);
  }
}

// ========================================
// 全消し虹色演出
// ========================================

void rainbowEffect() {

  for (uint8_t t = 0; t < 100; t++) {

    for (uint8_t p = 0; p < 64; p++) {

      uint8_t x = p & 7;
      uint8_t y = p >> 3;

      uint16_t hue =
        (uint32_t)t * 1800UL +
        (uint32_t)(x + y) * 5000UL;

      pixels.setPixelColor(
        ledIndex(x, y),
        pixels.ColorHSV(
          hue, 255, BRIGHTNESS
        )
      );
    }

    pixels.show();

    smartDelay(20);
  }

  // フェードアウト
  for (int8_t v = BRIGHTNESS; v >= 0; v--) {

    for (uint8_t p = 0; p < 64; p++) {

      uint8_t x = p & 7;
      uint8_t y = p >> 3;

      uint16_t hue =
        99UL * 1800UL +
        (uint32_t)(x + y) * 5000UL;

      pixels.setPixelColor(
        ledIndex(x, y),
        pixels.ColorHSV(hue, 255, v)
      );
    }

    pixels.show();

    smartDelay(30);
  }

  pixels.clear();
  pixels.show();
}

// ========================================
// 統計表示
// ========================================

void printStats() {

  Serial.println(F("--------------------"));

  Serial.print(F("Game: "));
  Serial.println(gameCount);

  Serial.print(F("Turns: "));
  Serial.println(totalTurns);

  Serial.print(F("Max chain: "));
  Serial.println(maxChainRecord);

  Serial.print(F("All clear: "));
  Serial.println(allClearCount);

  for (uint8_t c = 1;
       c <= maxChainRecord; c++) {

    Serial.print(c);
    Serial.print(F(" chain: "));
    Serial.println(chainCount[c]);
  }

  Serial.println(F("--------------------"));
}

// ========================================
// 表示用連鎖処理
// ========================================

void resolveAnimated() {

  uint8_t chain = 0;

  uint8_t marked[64];

  while (true) {

    while (gravity(field)) {

      drawField();
      pixels.show();

      smartDelay(GRAVITY_DELAY);
    }

    uint8_t count = findMatches(
      field, marked
    );

    if (!count)
      break;

    chain++;

    Serial.print(chain);
    Serial.println(F(" CHAIN!"));

    chainEffect(marked, chain);

    for (uint8_t p = 0; p < 64; p++) {

      if (marked[p])
        field[p] = 0;
    }

    drawField();
    pixels.show();

    smartDelay(180);
  }

  if (chain) {

    chainCount[chain]++;

    if (chain > maxChainRecord) {

      maxChainRecord = chain;

      Serial.print(F("NEW RECORD: "));
      Serial.print(chain);
      Serial.println(F(" CHAIN!"));
    }

    if (isEmpty(field)) {

      allClearCount++;

      Serial.println(F("ALL CLEAR!"));

      rainbowEffect();
    }
  }

  if (chain >= 2)
    printStats();
}

// ========================================
// 落下アニメーション
// ========================================

void dropPair(
  uint8_t c1, uint8_t c2,
  uint8_t x, uint8_t rot
) {

  int8_t targetY = landingY(
    field, x, rot
  );

  if (targetY == -99)
    return;

  for (int8_t y = -2; y <= targetY; y++) {

    drawField();

    drawPuyo(
      x, y, c1, BRIGHTNESS
    );

    drawPuyo(
      x + dx[rot],
      y + dy[rot],
      c2,
      BRIGHTNESS
    );

    pixels.show();

    smartDelay(FALL_DELAY);
  }

  field[(targetY << 3) | x] = c1;

  uint8_t x2 = x + dx[rot];
  uint8_t y2 = targetY + dy[rot];

  field[(y2 << 3) | x2] = c2;

  resolveAnimated();

  drawField();
  pixels.show();

  smartDelay(TURN_DELAY);
}

// ========================================
// 新しいゲーム
// ========================================

void prepareNewGame() {

  memset(field, 0, 64);

  current1 = random(1, COLOR_COUNT + 1);
  current2 = random(1, COLOR_COUNT + 1);

  next1 = random(1, COLOR_COUNT + 1);
  next2 = random(1, COLOR_COUNT + 1);

  startSearch(
    field,
    current1, current2,
    next1, next2
  );
}

// ========================================
// ゲームオーバー
// ========================================

void gameOver() {

  Serial.println(F("GAME OVER"));

  printStats();

  ai.active = false;

  // 上から1段ずつ消去
  for (uint8_t y = 0; y < 8; y++) {

    for (uint8_t x = 0; x < 8; x++)
      field[(y << 3) | x] = 0;

    drawField();
    pixels.show();

    delay(120);
  }

  gameCount++;

  prepareNewGame();

  smartDelay(800);

  Serial.print(F("NEW GAME: "));
  Serial.println(gameCount);
}

// ========================================
// 初期化
// ========================================

void setup() {

  Serial.begin(115200);

  pixels.begin();
  pixels.setBrightness(255);

  pixels.clear();
  pixels.show();

  Serial.println(
    F("PUYO AUTO PLAYER V5.2 UNO")
  );

  // アナログノイズによる乱数初期化
  initializeRandom();

  prepareNewGame();
}

// ========================================
// メインループ
// ========================================

void loop() {

  unsigned long waitTime =
    completeSearch();

  printSearchTime(waitTime);

  if (!ai.found) {

    gameOver();
    return;
  }

  uint8_t x = ai.bestX;
  uint8_t rot = ai.bestRot;

  uint8_t c1 = current1;
  uint8_t c2 = current2;

  uint8_t n1 = next1;
  uint8_t n2 = next2;

  uint8_t nn1 =
    random(1, COLOR_COUNT + 1);

  uint8_t nn2 =
    random(1, COLOR_COUNT + 1);

  // 現在の手を高速シミュレーション
  Board predicted;

  memcpy(predicted, field, 64);

  long dummyScore;

  if (!simulateMove(
    predicted,
    c1, c2,
    x, rot,
    dummyScore
  )) {

    gameOver();
    return;
  }

  // 次の手の探索を開始
  startSearch(
    predicted,
    n1, n2,
    nn1, nn2
  );

  current1 = n1;
  current2 = n2;

  next1 = nn1;
  next2 = nn2;

  totalTurns++;

  // アニメーション中にAI探索
  dropPair(c1, c2, x, rot);

  // 予測盤面と実際の盤面を照合
  if (memcmp(field, predicted, 64) != 0) {

    Serial.println(
      F("Prediction mismatch!")
    );

    startSearch(
      field,
      current1, current2,
      next1, next2
    );
  }
}

パラメータ調整

定数 初期値 意味
COLOR_COUNT 5 色数(3〜5)
BRIGHTNESS 10 通常輝度
FLASH_MIN_BRIGHTNESS 5 点滅最低輝度
FLASH_BRIGHTNESS 40 点滅最大輝度
FLASH_COUNT 3 点滅回数
PULSE_DELAY 5 点滅1サンプルの待機時間(ms)
FALL_DELAY 100 落下1マスの待機時間(ms)
GRAVITY_DELAY 90 消去後の落下1マスの待機時間(ms)
TURN_DELAY 0 連鎖処理終了後の待機時間(ms)
POTENTIAL_WEIGHT 100 潜在連鎖の評価係数

POTENTIAL_WEIGHT を増やすと潜在連鎖を重視しますが、発火を温存しすぎる可能性があります。色数が多いほど一般に同色をつなげにくくなります。輝度は電源容量と眩しさに合わせて調整してください。

シリアルモニタの AI CPU は分割探索の処理時間の積算、Elapsed は探索開始から完了までの経過時間、Extra wait はアニメーション終了後に追加で必要となった探索時間です。最大連鎖数と各連鎖の発生回数はゲームオーバー後も保持されますが、電源を切るとリセットされます。

おわりに

64個のLEDだけでも、積み上がりと連鎖の時間変化によって、単なる点灯パターンとは異なる、見ていて飽きにくい卓上ディスプレイを作ることができました。

限られた計算資源でも、表示用と計算用の処理を分け、待機時間を探索に利用し、不要な候補を省くことで、実用的な自動プレイが可能になります。ときどき発生する大連鎖を眺めるのが楽しい作品です。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?