ぬるーむ

Unity初心者が誰もが知っているゲームの模倣をしています。個人的な備忘録ですが、入門書を読み終えたばかりの初心者の方は「こんなへなちょこでもいいのか!」「俺の方がうまく作れる」と作成意欲がわいたりするかもしれません。

Unityでぷよぷよを作ってみた 4


スポンサードリンク

ぷよ同士をくっつける

くっついている方向を4ビットの整数で表す。

  • 上: 1(0b0001)
  • 右: 2(0b0010)
  • 下: 4(0b0100)
  • 左: 8(0b1000)
  • 上 + 右: 1 + 2 = 3(0b0011)
  • 上 + 下: 1 + 4 = 5(0b0101)
  • 上 + 左: 1 + 8 = 9(0b1001)
  • 右 + 下: 2 + 4 = 6(0b0110)
  • 右 + 左: 2 + 8 = 10(0b1010)
  • 下 + 左: 4 + 8 = 12(0b1100)
  • 上 + 右 + 下: 1 + 2 + 4 = 7(0b0111)
  • 上 + 右 + 左: 1 + 2 + 8 = 11(0b1011)
  • 上 + 下 + 左: 1 + 4 + 8 = 13(0b1101)
  • 右 + 下 + 左: 2 + 4 + 8 = 14(0b1110)
  • 上 + 右 + 下 + 左: 1 + 2 + 4 + 8 = 15(0b1111)

こうすることによりくっついている方向の番号を足し合わせることで任意の画像を取り出せるようになる。

f:id:Nullsuke:20201025234738p:plain
くっついている方向を整数で表す

private static readonly int width = 6;
private static readonly int height = 14;
private static readonly Puyo[,] field = new Puyo[width, height];
private static readonly int[,] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };

//ぷよ同士をくっつける
public void StickPuyoes()
{
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            var p = field[x, y];

            if (p == null) continue;

            int stickType = GetStickType(x, y);

            p.ChangeSprite(stickType);
        }
    }
}

//ぷよがくっついている方向を整数で取得
private int GetStickType(int x, int y)
{
    var p = field[x, y];
    int stickType = 0;

    for (int i = 0; i < dirs.GetLength(0); i++)
    {
        int nx = x + dirs[i, 0];
        int ny = y + dirs[i, 1];

        if (!IsInside(nx, ny)) continue;

        var np = field[nx, ny];

        if (np != null && p.Color == np.Color)
        {
            //上下左右、それぞれに割り当てた数を足していく
            stickType += (int)Mathf.Pow(2, i);
        }
    }

    return stickType;
}

//フィールドの内側にあるか判定
public bool IsInside(int x, int y)
{
    if (x < 0 || x >= width || y < 0 || y >= height)
    {
        return false;
    }

    return true;
}
private SpriteRenderer spriteRenderer;

//ぷよの画像を変える
public void ChangeSprite(int stickType)
{
    //組ぷよを回転させると、一緒にぷよも回転しているので角度を元に戻す
    transform.rotation = Quaternion.identity;
    spriteRenderer.sprite = sprites[stickType];
}

private void Awake()
{
    spriteRenderer = GetComponent<SpriteRenderer>();
    sprites = Resources.LoadAll<Sprite>(Color.ToString() + "Puyoes");
}