【第二回】C#でテトリス作成

【第二回】C#でテトリス作成

目次

前回のおさらい
Controller実装
セッションの有効化
View実装
実行
まとめ

前回のおさらい

前回はModel部分の作成をしました。
具体的には以下のクラスとなります。
1,Tetrimino.cs テトリミノ(落ちてくるブロック)
2,GameBoard.cs ゲーム盤の管理
3,TetrisGame.cs ゲーム全体の制御
今回はControllerとViewを作成していきます。

Controller実装

まずは GameControllerを実装していきます。
Controllersフォルダに新しいクラスを作成し、以下のコードを書きます。

<code>using Microsoft.AspNetCore.Mvc;
using TetrisGame.Models;
using System.Text.Json;
using System;
using System.Threading.Tasks;

namespace TetrisGame.Controllers
{
    /// &lt;summary&gt;
    /// テトリスゲームのWebAPI制御を行うコントローラー
    /// &lt;/summary&gt;
    public class GameController : Controller
    {
        // セッションキー定数
        private const string GAME_SESSION_KEY = "TetrisGameState";
        private const string GAME_ID_KEY = "TetrisGameId";

        /// &lt;summary&gt;
        /// ゲームのメイン画面を表示
        /// &lt;/summary&gt;
        /// &lt;returns&gt;ゲーム画面のView&lt;/returns&gt;
        public IActionResult Index()
        {
            try
            {
                // 新しいゲームセッションを開始
                var gameId = Guid.NewGuid().ToString();
                HttpContext.Session.SetString(GAME_ID_KEY, gameId);

                // セッション情報をViewに渡す
                ViewBag.GameId = gameId;
                ViewBag.SessionTimeout = 30; // デフォルト値30分

                Console.WriteLine($"&#91;DEBUG] Index: 新しいセッション開始 - GameId: {gameId}");
                return View();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] Index例外: {ex.Message}");
                // エラーページまたはデフォルト状態でViewを返す
                ViewBag.GameId = Guid.NewGuid().ToString();
                ViewBag.SessionTimeout = 30;
                return View();
            }
        }

        /// &lt;summary&gt;
        /// 新しいゲームを開始
        /// &lt;/summary&gt;
        /// &lt;returns&gt;ゲーム初期状態のJSON&lt;/returns&gt;
        &#91;HttpPost]
        public IActionResult StartNewGame()
        {
            Console.WriteLine("&#91;DEBUG] StartNewGame開始");

            try
            {
                var game = new Models.TetrisGame();
                Console.WriteLine($"&#91;DEBUG] ゲーム作成成功: Board={game.Board.Board?.Length}x{game.Board.Board?&#91;0]?.Length}");
                Console.WriteLine($"&#91;DEBUG] CurrentPiece: {game.CurrentPiece?.Type} at ({game.CurrentPiece?.X},{game.CurrentPiece?.Y})");

                SaveGameToSession(game);
                Console.WriteLine("&#91;DEBUG] セッション保存完了");

                var gameState = GetGameStateForClient(game);
                Console.WriteLine("&#91;DEBUG] クライアント状態作成完了");

                return Json(new
                {
                    success = true,
                    gameState = gameState,
                    message = "新しいゲームを開始しました"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] StartNewGame例外: {ex.Message}");
                Console.WriteLine($"&#91;ERROR] スタックトレース: {ex.StackTrace}");
                return Json(new
                {
                    success = false,
                    error = ex.Message
                });
            }
        }

        /// &lt;summary&gt;
        /// 現在のゲーム状態を取得
        /// &lt;/summary&gt;
        /// &lt;returns&gt;ゲーム状態のJSON&lt;/returns&gt;
        &#91;HttpGet]
        public IActionResult GetGameState()
        {
            try
            {
                var game = LoadGameFromSession();
                if (game == null)
                {
                    return Json(new
                    {
                        success = false,
                        error = "ゲームが見つかりません。新しいゲームを開始してください。",
                        needsNewGame = true
                    });
                }

                var gameState = GetGameStateForClient(game);

                return Json(new
                {
                    success = true,
                    gameState = gameState
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] GetGameState例外: {ex.Message}");
                return Json(new
                {
                    success = false,
                    error = ex.Message,
                    needsNewGame = true
                });
            }
        }

        /// &lt;summary&gt;
        /// テトロミノを左に移動
        /// &lt;/summary&gt;
        /// &lt;returns&gt;移動後のゲーム状態&lt;/returns&gt;
        &#91;HttpPost]
        public IActionResult MoveLeft()
        {
            return HandleGameAction(game =&gt; game.MoveLeft(), "左移動");
        }

        /// &lt;summary&gt;
        /// テトロミノを右に移動
        /// &lt;/summary&gt;
        /// &lt;returns&gt;移動後のゲーム状態&lt;/returns&gt;
        &#91;HttpPost]
        public IActionResult MoveRight()
        {
            return HandleGameAction(game =&gt; game.MoveRight(), "右移動");
        }

        /// &lt;summary&gt;
        /// テトロミノを下に移動(ソフトドロップ)
        /// &lt;/summary&gt;
        /// &lt;returns&gt;移動後のゲーム状態&lt;/returns&gt;
        &#91;HttpPost]
        public IActionResult MoveDown()
        {
            return HandleGameAction(game =&gt; game.MoveDown(), "下移動");
        }

        /// &lt;summary&gt;
        /// テトロミノを回転
        /// &lt;/summary&gt;
        /// &lt;returns&gt;回転後のゲーム状態&lt;/returns&gt;
        &#91;HttpPost]
        public IActionResult RotatePiece()
        {
            return HandleGameAction(game =&gt; game.RotatePiece(), "回転");
        }

        /// &lt;summary&gt;
        /// ハードドロップ(一気に底まで)
        /// &lt;/summary&gt;
        /// &lt;returns&gt;ドロップ後のゲーム状態&lt;/returns&gt;
        &#91;HttpPost]
        public IActionResult HardDrop()
        {
            return HandleGameAction(game =&gt;
            {
                var dropDistance = game.HardDrop();
                return dropDistance &gt;= 0; // 0でも成功とする
            }, "ハードドロップ");
        }

        /// &lt;summary&gt;
        /// ゲームを一時停止/再開
        /// &lt;/summary&gt;
        /// &lt;returns&gt;操作後のゲーム状態&lt;/returns&gt;
        &#91;HttpPost]
        public IActionResult TogglePause()
        {
            try
            {
                var game = LoadGameFromSession();
                if (game == null)
                {
                    return Json(new { success = false, error = "ゲームが見つかりません", needsNewGame = true });
                }

                game.TogglePause();
                SaveGameToSession(game);

                var gameState = GetGameStateForClient(game);

                return Json(new
                {
                    success = true,
                    gameState = gameState,
                    message = game.IsPaused ? "ゲームを一時停止しました" : "ゲームを再開しました"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] TogglePause例外: {ex.Message}");
                return Json(new { success = false, error = ex.Message });
            }
        }

        /// &lt;summary&gt;
        /// ゲームをリセット
        /// &lt;/summary&gt;
        /// &lt;returns&gt;リセット後のゲーム状態&lt;/returns&gt;
        &#91;HttpPost]
        public IActionResult ResetGame()
        {
            try
            {
                var game = LoadGameFromSession();
                if (game == null)
                {
                    // ゲームが存在しない場合は新規作成
                    return StartNewGame();
                }

                game.Reset();
                SaveGameToSession(game);

                var gameState = GetGameStateForClient(game);

                return Json(new
                {
                    success = true,
                    gameState = gameState,
                    message = "ゲームをリセットしました"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] ResetGame例外: {ex.Message}");
                return Json(new { success = false, error = ex.Message });
            }
        }

        /// &lt;summary&gt;
        /// ゲーム状態を更新(自動落下など)
        /// &lt;/summary&gt;
        /// &lt;returns&gt;更新後のゲーム状態&lt;/returns&gt;
        &#91;HttpPost]
        public IActionResult UpdateGame()
        {
            try
            {
                var game = LoadGameFromSession();
                if (game == null)
                {
                    return Json(new { success = false, error = "ゲームが見つかりません", needsNewGame = true });
                }

                // ゲーム状態を更新(自動落下処理)
                game.Update();
                SaveGameToSession(game);

                var gameState = GetGameStateForClient(game);

                return Json(new
                {
                    success = true,
                    gameState = gameState
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] UpdateGame例外: {ex.Message}");
                return Json(new { success = false, error = ex.Message });
            }
        }

        #region プライベートヘルパーメソッド

        /// &lt;summary&gt;
        /// ゲームアクションの共通処理
        /// &lt;/summary&gt;
        /// &lt;param name="action"&gt;実行するアクション&lt;/param&gt;
        /// &lt;param name="actionName"&gt;アクション名(ログ用)&lt;/param&gt;
        /// &lt;returns&gt;処理結果のJSON&lt;/returns&gt;
        private IActionResult HandleGameAction(Func&lt;Models.TetrisGame, bool&gt; action, string actionName)
        {
            try
            {
                var game = LoadGameFromSession();
                if (game == null)
                {
                    return Json(new { success = false, error = "ゲームが見つかりません", needsNewGame = true });
                }

                if (game.IsGameOver)
                {
                    return Json(new
                    {
                        success = false,
                        error = "ゲームオーバーです",
                        gameState = GetGameStateForClient(game)
                    });
                }

                if (game.IsPaused)
                {
                    return Json(new
                    {
                        success = false,
                        error = "ゲームが一時停止中です",
                        gameState = GetGameStateForClient(game)
                    });
                }

                // アクションを実行
                bool actionResult = action(game);

                // セッションに保存
                SaveGameToSession(game);

                // クライアント用の状態データを取得
                var gameState = GetGameStateForClient(game);

                return Json(new
                {
                    success = true,
                    actionResult = actionResult,
                    gameState = gameState,
                    message = $"{actionName}を実行しました"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] HandleGameAction ({actionName}) 例外: {ex.Message}");
                return Json(new
                {
                    success = false,
                    error = ex.Message
                });
            }
        }

        /// &lt;summary&gt;
        /// セッションからゲーム状態を読み込み
        /// &lt;/summary&gt;
        /// &lt;returns&gt;ゲームインスタンス、または null&lt;/returns&gt;
        private Models.TetrisGame? LoadGameFromSession()
        {
            try
            {
                var gameJson = HttpContext.Session.GetString(GAME_SESSION_KEY);
                if (string.IsNullOrEmpty(gameJson))
                {
                    Console.WriteLine("&#91;DEBUG] セッションにゲームデータが見つかりません");
                    return null;
                }

                // JSONからゲームオブジェクトを復元
                var options = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    WriteIndented = false
                };

                var game = JsonSerializer.Deserialize&lt;Models.TetrisGame&gt;(gameJson, options);
                Console.WriteLine($"&#91;DEBUG] セッションからゲーム復元成功: {game?.ToString()}");
                return game;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] セッション読み込みエラー: {ex.Message}");
                // デシリアライズに失敗した場合はnullを返す
                return null;
            }
        }

        /// &lt;summary&gt;
        /// ゲーム状態をセッションに保存
        /// &lt;/summary&gt;
        /// &lt;param name="game"&gt;保存するゲームインスタンス&lt;/param&gt;
        private void SaveGameToSession(Models.TetrisGame game)
        {
            try
            {
                var options = new JsonSerializerOptions
                {
                    WriteIndented = false,
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
                };

                var gameJson = JsonSerializer.Serialize(game, options);
                HttpContext.Session.SetString(GAME_SESSION_KEY, gameJson);

                Console.WriteLine($"&#91;DEBUG] セッション保存成功: データサイズ {gameJson.Length} 文字");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] セッション保存エラー: {ex.Message}");
                throw; // エラーを再スロー
            }
        }

        /// &lt;summary&gt;
        /// クライアント用のゲーム状態データを作成
        /// &lt;/summary&gt;
        /// &lt;param name="game"&gt;ゲームインスタンス&lt;/param&gt;
        /// &lt;returns&gt;クライアント用の状態オブジェクト&lt;/returns&gt;
        private object GetGameStateForClient(Models.TetrisGame game)
        {
            try
            {
                var gameState = new
                {
                    // ゲーム盤の状態
                    board = game.Board.Board,

                    // 現在のピース情報
                    currentPiece = game.CurrentPiece != null ? new
                    {
                        type = game.CurrentPiece.Type.ToString(),
                        x = game.CurrentPiece.X,
                        y = game.CurrentPiece.Y,
                        rotation = game.CurrentPiece.Rotation,
                        shape = game.CurrentPiece.Shape
                    } : null,

                    // 次のピース情報
                    nextPiece = game.NextPiece != null ? new
                    {
                        type = game.NextPiece.Type.ToString(),
                        shape = game.NextPiece.Shape
                    } : null,

                    // スコア等の情報
                    score = game.Score,
                    lines = game.Lines,
                    level = game.Level,

                    // ゲーム状態
                    isGameOver = game.IsGameOver,
                    isPaused = game.IsPaused,

                    // タイミング情報
                    dropInterval = game.DropInterval,
                    lastDropTime = game.LastDropTime.ToString("yyyy-MM-dd HH:mm:ss.fff"),

                    // 追加情報
                    ghostY = game.GetGhostPieceY() // ゴーストピース用
                };

                return gameState;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"&#91;ERROR] GetGameStateForClient例外: {ex.Message}");
                throw;
            }
        }

        #endregion
    }
}</code>

セッションの有効化

続けてセッション機能の有効化を行います。
セッションを有効化するためにProgram.cs の修正を以下のように修正します。

<code>var builder = WebApplication.CreateBuilder(args);

// MVC サービスを追加
builder.Services.AddControllersWithViews();

// セッション機能を追加
builder.Services.AddSession(options =&gt;
{
    options.IdleTimeout = TimeSpan.FromMinutes(30); // 30分でタイムアウト
    options.Cookie.HttpOnly = true; // XSS対策
    options.Cookie.IsEssential = true; // GDPR対策
    options.Cookie.Name = "TetrisGame.Session"; // セッションCookie名
});

// メモリキャッシュを追加(セッション用)
builder.Services.AddMemoryCache();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

// セッション機能を有効化(重要:UseRoutingの後、UseEndpointsの前)
app.UseSession();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Game}/{action=Index}/{id?}"); // デフォルトをGameControllerに変更

app.Run();</code>

View実装

続けてViewの実装を行っていきます。
まずは「Views」フォルダを右クリックして追加>新しいフォルダーから「Game」フォルダを作成します。
続けて「Game」フォルダを右クリックして追加>ビューを作成し名前をIndexとして作成します。
作成したIndexに以下のコードを書きます。

<code>@{
    ViewData&#91;"Title"] = "テトリスゲーム";
}

&lt;!DOCTYPE html&gt;
&lt;html lang="ja"&gt;
&lt;head&gt;
    &lt;meta charset="utf-8" /&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
    &lt;title&gt;@ViewData&#91;"Title"]&lt;/title&gt;

    &lt;style type="text/css"&gt;
        /* ========== 基本スタイル ========== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'メイリオ', 'Hiragino Sans', Arial, sans-serif;
            background-color: #0a0a0a;
            color: white;
            padding: 20px;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
        }

        /* ========== ヘッダー ========== */
        .game-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .game-title {
            font-size: 2.5rem;
            color: #00ffff;
            text-shadow: 0 0 10px #00ffff;
            margin-bottom: 10px;
        }

        /* ========== レイアウト ========== */
        .game-content {
            display: flex;
            flex-direction: row;
            gap: 30px;
            margin-bottom: 30px;
            justify-content: center;
        }

        .game-area {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        #tetris-board {
            border: 3px solid #00ffff;
            background-color: #111;
            box-shadow: 0 0 20px rgba(0, 255, 255, 0.3);
        }

        /* ========== 情報パネル ========== */
        .info-panel {
            background-color: #1a1a1a;
            border: 2px solid #333;
            border-radius: 10px;
            padding: 20px;
            width: 300px;
            height: fit-content;
        }

        .info-section {
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #333;
        }

            .info-section:last-child {
                border-bottom: none;
                margin-bottom: 0;
            }

        .info-title {
            font-size: 0.9rem;
            color: #00ffff;
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .info-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: white;
        }

        .next-piece-area {
            text-align: center;
        }

        #next-piece {
            border: 2px solid #555;
            background-color: #0f0f0f;
            margin: 10px auto;
            display: block;
        }

        /* ========== ボタン ========== */
        .button-area {
            text-align: center;
            margin-bottom: 30px;
        }

        .game-button {
            background: linear-gradient(135deg, #00ffff, #0080ff);
            border: none;
            border-radius: 8px;
            color: white;
            padding: 12px 24px;
            margin: 0 5px 5px 5px;
            font-size: 1rem;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

            .game-button:hover {
                background: linear-gradient(135deg, #0080ff, #0060df);
                transform: translateY(-2px);
                box-shadow: 0 5px 15px rgba(0, 255, 255, 0.4);
            }

            .game-button:active {
                transform: translateY(0);
            }

            .game-button:disabled {
                background: #666;
                cursor: not-allowed;
                transform: none;
                box-shadow: none;
            }

        /* ========== 操作説明 ========== */
        .controls-section {
            background-color: #1a1a1a;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .controls-title {
            color: #00ffff;
            margin-bottom: 15px;
            font-size: 1.2rem;
        }

        .control-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .control-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #333;
        }

            .control-item:last-child {
                border-bottom: none;
            }

        .control-key {
            font-weight: bold;
            color: #00ffff;
            font-family: 'Courier New', monospace;
        }

        .control-action {
            color: #ccc;
        }

        /* ========== ステータスメッセージ ========== */
        .status-message {
            padding: 15px;
            border-radius: 8px;
            margin: 20px auto;
            max-width: 500px;
            text-align: center;
            font-weight: bold;
            display: none;
        }

        .status-success {
            background-color: rgba(76, 175, 80, 0.2);
            border: 1px solid #4caf50;
            color: #4caf50;
        }

        .status-error {
            background-color: rgba(244, 67, 54, 0.2);
            border: 1px solid #f44336;
            color: #f44336;
        }

        .status-info {
            background-color: rgba(33, 150, 243, 0.2);
            border: 1px solid #2196f3;
            color: #2196f3;
        }

        /* ========== レスポンシブデザイン(修正版) ========== */
        /* タブレット用 */
        @@media screen and (max-width: 1024px) {
            .container {
                padding: 0 10px;
            }

            .game-content {
                gap: 20px;
            }

            .info-panel {
                width: 250px;
            }
        }

        /* スマートフォン用 */
        @@media screen and (max-width: 768px) {
            body {
                padding: 10px;
            }

            .game-title {
                font-size: 2rem;
            }

            .game-content {
                flex-direction: column;
                align-items: center;
                gap: 20px;
            }

            .info-panel {
                width: 100%;
                max-width: 400px;
            }

            #tetris-board {
                width: 280px;
                height: 560px;
            }

            .game-button {
                display: block;
                margin: 5px auto;
                width: 200px;
                padding: 15px 24px;
            }

            .control-list {
                display: grid;
                grid-template-columns: 1fr;
                gap: 8px;
            }
        }

        /* 小さいスマートフォン用 */
        @@media screen and (max-width: 480px) {
            .game-title {
                font-size: 1.5rem;
            }

            #tetris-board {
                width: 250px;
                height: 500px;
            }

            .info-panel {
                padding: 15px;
            }

            .info-value {
                font-size: 1.2rem;
            }

            .game-button {
                width: 100%;
                max-width: 280px;
            }
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class="container"&gt;
        &lt;header class="game-header"&gt;
            &lt;h1 class="game-title"&gt;🎮 TETRIS GAME 🎮&lt;/h1&gt;
        &lt;/header&gt;

        &lt;main class="game-content"&gt;
            &lt;div class="game-area"&gt;
                &lt;canvas id="tetris-board" width="300" height="600"&gt;
                    お使いのブラウザはCanvasをサポートしていません。
                &lt;/canvas&gt;
            &lt;/div&gt;

            &lt;aside class="info-panel"&gt;
                &lt;div class="info-section"&gt;
                    &lt;div class="info-title"&gt;Score&lt;/div&gt;
                    &lt;div class="info-value" id="score-display"&gt;0&lt;/div&gt;
                &lt;/div&gt;

                &lt;div class="info-section"&gt;
                    &lt;div class="info-title"&gt;Level&lt;/div&gt;
                    &lt;div class="info-value" id="level-display"&gt;1&lt;/div&gt;
                &lt;/div&gt;

                &lt;div class="info-section"&gt;
                    &lt;div class="info-title"&gt;Lines&lt;/div&gt;
                    &lt;div class="info-value" id="lines-display"&gt;0&lt;/div&gt;
                &lt;/div&gt;

                &lt;div class="info-section next-piece-area"&gt;
                    &lt;div class="info-title"&gt;Next Piece&lt;/div&gt;
                    &lt;canvas id="next-piece" width="120" height="120"&gt;&lt;/canvas&gt;
                &lt;/div&gt;

                &lt;div class="info-section"&gt;
                    &lt;div class="info-title"&gt;Status&lt;/div&gt;
                    &lt;div class="info-value" id="game-status"&gt;準備中&lt;/div&gt;
                &lt;/div&gt;
            &lt;/aside&gt;
        &lt;/main&gt;

        &lt;div class="button-area"&gt;
            &lt;button id="start-btn" class="game-button"&gt;🎮 ゲーム開始&lt;/button&gt;
            &lt;button id="pause-btn" class="game-button" disabled&gt;⏸️ 一時停止&lt;/button&gt;
            &lt;button id="reset-btn" class="game-button"&gt;🔄 リセット&lt;/button&gt;
        &lt;/div&gt;

        &lt;section class="controls-section"&gt;
            &lt;h3 class="controls-title"&gt;🎯 操作方法&lt;/h3&gt;
            &lt;div class="control-list"&gt;
                &lt;div class="control-item"&gt;
                    &lt;span class="control-key"&gt;← → (A D)&lt;/span&gt;
                    &lt;span class="control-action"&gt;左右移動&lt;/span&gt;
                &lt;/div&gt;
                &lt;div class="control-item"&gt;
                    &lt;span class="control-key"&gt;↓ (S)&lt;/span&gt;
                    &lt;span class="control-action"&gt;高速落下&lt;/span&gt;
                &lt;/div&gt;
                &lt;div class="control-item"&gt;
                    &lt;span class="control-key"&gt;↑ (W)&lt;/span&gt;
                    &lt;span class="control-action"&gt;回転&lt;/span&gt;
                &lt;/div&gt;
                &lt;div class="control-item"&gt;
                    &lt;span class="control-key"&gt;Space&lt;/span&gt;
                    &lt;span class="control-action"&gt;ハードドロップ&lt;/span&gt;
                &lt;/div&gt;
                &lt;div class="control-item"&gt;
                    &lt;span class="control-key"&gt;P&lt;/span&gt;
                    &lt;span class="control-action"&gt;一時停止&lt;/span&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/section&gt;

        &lt;div id="status-message" class="status-message"&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;script&gt;
        console.log('🎮 テトリス読み込み開始');

        // グローバル変数
        let gameState = null;
        let isGameRunning = false;
        let gameLoopTimer = null;
        let autoDropTimer = null;
        let lastUpdateTime = 0;
        let keyPressed = {};

        // DOM要素
        const elements = {
            tetrisBoard: document.getElementById('tetris-board'),
            nextPiece: document.getElementById('next-piece'),
            scoreDisplay: document.getElementById('score-display'),
            levelDisplay: document.getElementById('level-display'),
            linesDisplay: document.getElementById('lines-display'),
            gameStatus: document.getElementById('game-status'),
            startBtn: document.getElementById('start-btn'),
            pauseBtn: document.getElementById('pause-btn'),
            resetBtn: document.getElementById('reset-btn'),
            statusMessage: document.getElementById('status-message')
        };

        const boardCtx = elements.tetrisBoard.getContext('2d');
        const nextCtx = elements.nextPiece.getContext('2d');

        // 初期化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('📋 DOM読み込み完了');
            setupEventListeners();
            initializeCanvas();
            console.log('✅ 初期化完了');
        });

        function setupEventListeners() {
            elements.startBtn.addEventListener('click', startNewGame);
            elements.pauseBtn.addEventListener('click', togglePause);
            elements.resetBtn.addEventListener('click', resetGame);

            // キーボードイベント(重複防止機能付き)
            document.addEventListener('keydown', (e) =&gt; {
                if (keyPressed&#91;e.key]) return; // 重複防止
                keyPressed&#91;e.key] = true;
                handleKeyPress(e);
            });

            document.addEventListener('keyup', (e) =&gt; {
                keyPressed&#91;e.key] = false;
            });

            window.addEventListener('beforeunload', stopAutoDropSystem);
        }

        function initializeCanvas() {
            // メインボード初期化
            boardCtx.fillStyle = '#111';
            boardCtx.fillRect(0, 0, elements.tetrisBoard.width, elements.tetrisBoard.height);

            // ネクストピース初期化
            nextCtx.fillStyle = '#0f0f0f';
            nextCtx.fillRect(0, 0, elements.nextPiece.width, elements.nextPiece.height);

            drawGrid();
        }

        function drawGrid() {
            const cellWidth = elements.tetrisBoard.width / 10;
            const cellHeight = elements.tetrisBoard.height / 20;

            boardCtx.strokeStyle = '#333';
            boardCtx.lineWidth = 1;

            // 縦線
            for (let i = 0; i &lt;= 10; i++) {
                const x = i * cellWidth;
                boardCtx.beginPath();
                boardCtx.moveTo(x, 0);
                boardCtx.lineTo(x, elements.tetrisBoard.height);
                boardCtx.stroke();
            }

            // 横線
            for (let i = 0; i &lt;= 20; i++) {
                const y = i * cellHeight;
                boardCtx.beginPath();
                boardCtx.moveTo(0, y);
                boardCtx.lineTo(elements.tetrisBoard.width, y);
                boardCtx.stroke();
            }
        }

        async function startNewGame() {
            console.log('🎮 ゲーム開始');
            elements.gameStatus.textContent = '開始中...';

            try {
                const response = await fetch('/Game/StartNewGame', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                const data = await response.json();
                console.log('📡 レスポンス:', data);

                if (data.success) {
                    gameState = data.gameState;
                    isGameRunning = true;
                    lastUpdateTime = Date.now();

                    updateUI();
                    updateButtonStates(true);
                    startAutoDropSystem();

                    showStatusMessage('ゲーム開始!', 'success');
                    console.log('✅ ゲーム開始成功');
                } else {
                    showStatusMessage('エラー: ' + data.error, 'error');
                }
            } catch (error) {
                console.error('❌ 通信エラー:', error);
                showStatusMessage('通信エラー', 'error');
            }
        }

        function startAutoDropSystem() {
            console.log('⏰ 自動落下システム開始');
            stopAutoDropSystem();

            // 描画ループ(60FPS)
            gameLoopTimer = setInterval(() =&gt; {
                if (isGameRunning &amp;&amp; gameState &amp;&amp; !gameState.isGameOver &amp;&amp; !gameState.isPaused) {
                    updateUI();
                }
            }, 1000 / 60);

            // 自動落下ループ(0.5秒間隔)
            autoDropTimer = setInterval(async () =&gt; {
                if (isGameRunning &amp;&amp; gameState &amp;&amp; !gameState.isGameOver &amp;&amp; !gameState.isPaused) {
                    await performAutoUpdate();
                }
            }, 500);
        }

        function stopAutoDropSystem() {
            if (gameLoopTimer) {
                clearInterval(gameLoopTimer);
                gameLoopTimer = null;
                console.log('⏰ 描画ループ停止');
            }
            if (autoDropTimer) {
                clearInterval(autoDropTimer);
                autoDropTimer = null;
                console.log('⏰ 自動落下ループ停止');
            }
        }

        async function performAutoUpdate() {
            try {
                const response = await fetch('/Game/UpdateGame', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                const data = await response.json();

                if (data.success) {
                    const oldY = gameState.currentPiece?.y;
                    gameState = data.gameState;
                    const newY = gameState.currentPiece?.y;

                    if (oldY !== newY) {
                        console.log(`⬇️ 自動落下: Y ${oldY} → ${newY}`);
                    }

                    if (gameState.isGameOver) {
                        handleGameOver();
                    }

                    lastUpdateTime = Date.now();
                } else if (data.needsNewGame) {
                    console.log('🔄 ゲーム状態が見つかりません');
                    showStatusMessage('ゲームセッションが切れました', 'error');
                    isGameRunning = false;
                    updateButtonStates(false);
                    stopAutoDropSystem();
                }
            } catch (error) {
                console.error('❌ 自動更新エラー:', error);
            }
        }

        function handleGameOver() {
            console.log('💀 ゲームオーバー');
            stopAutoDropSystem();
            isGameRunning = false;
            updateUI();
            updateButtonStates(false);

            setTimeout(() =&gt; {
                const result = confirm(`ゲームオーバー!\n最終スコア: ${gameState.score.toLocaleString()}\n消去ライン数: ${gameState.lines}\nレベル: ${gameState.level}\n\nもう一度プレイしますか?`);
                if (result) {
                    startNewGame();
                }
            }, 1000);
        }

        async function handleKeyPress(event) {
            if (!isGameRunning || !gameState || gameState.isGameOver) return;

            // 一時停止中でもPキーは有効
            if (event.key.toLowerCase() === 'p') {
                togglePause();
                return;
            }

            if (gameState.isPaused) return;

            let endpoint = null;

            switch (event.key.toLowerCase()) {
                case 'arrowleft':
                case 'a':
                    endpoint = '/Game/MoveLeft';
                    break;
                case 'arrowright':
                case 'd':
                    endpoint = '/Game/MoveRight';
                    break;
                case 'arrowdown':
                case 's':
                    endpoint = '/Game/MoveDown';
                    break;
                case 'arrowup':
                case 'w':
                    endpoint = '/Game/RotatePiece';
                    break;
                case ' ':
                case 'spacebar':
                    endpoint = '/Game/HardDrop';
                    break;
                default:
                    return; // 無関係なキーは無視
            }

            if (endpoint) {
                event.preventDefault();
                await sendGameAction(endpoint);
            }
        }

        async function sendGameAction(endpoint) {
            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                const data = await response.json();

                if (data.success) {
                    gameState = data.gameState;
                    updateUI();
                    lastUpdateTime = Date.now();

                    // ゲームオーバーチェック
                    if (gameState.isGameOver) {
                        handleGameOver();
                    }
                } else if (data.needsNewGame) {
                    showStatusMessage('ゲームセッションが切れました', 'error');
                    isGameRunning = false;
                    updateButtonStates(false);
                    stopAutoDropSystem();
                }
            } catch (error) {
                console.error('❌ 操作エラー:', error);
            }
        }

        async function togglePause() {
            if (!gameState) return;

            try {
                const response = await fetch('/Game/TogglePause', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                const data = await response.json();

                if (data.success) {
                    gameState = data.gameState;
                    updateUI();
                    updateButtonStates(isGameRunning);
                    showStatusMessage(data.message, 'info');
                }
            } catch (error) {
                console.error('❌ 一時停止エラー:', error);
            }
        }

        async function resetGame() {
            console.log('🔄 リセット開始');
            stopAutoDropSystem();

            try {
                const response = await fetch('/Game/ResetGame', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                const data = await response.json();

                if (data.success) {
                    gameState = data.gameState;
                    isGameRunning = true;
                    lastUpdateTime = Date.now();

                    updateUI();
                    updateButtonStates(true);
                    startAutoDropSystem();

                    showStatusMessage('リセット完了', 'success');
                    console.log('✅ リセット完了');
                } else {
                    showStatusMessage('リセットに失敗しました', 'error');
                }
            } catch (error) {
                console.error('❌ リセットエラー:', error);
                showStatusMessage('リセットエラー', 'error');
            }
        }

        function updateUI() {
            if (!gameState) return;

            // スコア情報の更新
            elements.scoreDisplay.textContent = gameState.score.toLocaleString();
            elements.levelDisplay.textContent = gameState.level;
            elements.linesDisplay.textContent = gameState.lines;

            // ゲーム状態の表示
            if (gameState.isGameOver) {
                elements.gameStatus.textContent = 'ゲームオーバー';
                elements.gameStatus.style.color = '#ff4444';
            } else if (gameState.isPaused) {
                elements.gameStatus.textContent = '一時停止中';
                elements.gameStatus.style.color = '#ffaa44';
            } else {
                elements.gameStatus.textContent = 'プレイ中';
                elements.gameStatus.style.color = '#44ff44';
            }

            drawGameBoard();
            drawNextPiece();
        }

        function drawGameBoard() {
            // 背景をクリア
            boardCtx.fillStyle = '#111';
            boardCtx.fillRect(0, 0, elements.tetrisBoard.width, elements.tetrisBoard.height);

            if (gameState &amp;&amp; gameState.board) {
                const cellWidth = elements.tetrisBoard.width / 10;
                const cellHeight = elements.tetrisBoard.height / 20;

                // 固定されたブロックを描画
                for (let row = 0; row &lt; 20; row++) {
                    for (let col = 0; col &lt; 10; col++) {
                        const cellValue = gameState.board&#91;row]&#91;col];
                        if (cellValue &gt; 0) {
                            boardCtx.fillStyle = getBlockColor(cellValue);
                            boardCtx.fillRect(
                                col * cellWidth + 1,
                                row * cellHeight + 1,
                                cellWidth - 2,
                                cellHeight - 2
                            );
                        }
                    }
                }

                // ゴーストピースを描画(現在のピースがある場合)
                if (gameState.currentPiece &amp;&amp; gameState.ghostY !== undefined &amp;&amp; gameState.ghostY &gt; gameState.currentPiece.y) {
                    const piece = gameState.currentPiece;
                    boardCtx.fillStyle = 'rgba(255, 255, 255, 0.3)'; // 半透明の白

                    for (let row = 0; row &lt; 4; row++) {
                        for (let col = 0; col &lt; 4; col++) {
                            if (piece.shape&#91;row] &amp;&amp; piece.shape&#91;row]&#91;col]) {
                                const boardX = piece.x + col;
                                const boardY = gameState.ghostY + row;

                                if (boardX &gt;= 0 &amp;&amp; boardX &lt; 10 &amp;&amp; boardY &gt;= 0 &amp;&amp; boardY &lt; 20) {
                                    boardCtx.fillRect(
                                        boardX * cellWidth + 2,
                                        boardY * cellHeight + 2,
                                        cellWidth - 4,
                                        cellHeight - 4
                                    );
                                }
                            }
                        }
                    }
                }

                // 現在のピースを描画
                if (gameState.currentPiece) {
                    const piece = gameState.currentPiece;
                    boardCtx.fillStyle = getBlockColor(getTetrominoTypeNumber(piece.type));

                    for (let row = 0; row &lt; 4; row++) {
                        for (let col = 0; col &lt; 4; col++) {
                            if (piece.shape&#91;row] &amp;&amp; piece.shape&#91;row]&#91;col]) {
                                const boardX = piece.x + col;
                                const boardY = piece.y + row;

                                if (boardX &gt;= 0 &amp;&amp; boardX &lt; 10 &amp;&amp; boardY &gt;= 0 &amp;&amp; boardY &lt; 20) {
                                    boardCtx.fillRect(
                                        boardX * cellWidth + 1,
                                        boardY * cellHeight + 1,
                                        cellWidth - 2,
                                        cellHeight - 2
                                    );
                                }
                            }
                        }
                    }
                }
            }

            drawGrid();
        }

        function drawNextPiece() {
            // 背景をクリア
            nextCtx.fillStyle = '#0f0f0f';
            nextCtx.fillRect(0, 0, elements.nextPiece.width, elements.nextPiece.height);

            if (gameState &amp;&amp; gameState.nextPiece) {
                const piece = gameState.nextPiece;
                const cellSize = 25; // ネクストピース用のセルサイズ
                const offsetX = (elements.nextPiece.width - cellSize * 4) / 2;
                const offsetY = (elements.nextPiece.height - cellSize * 4) / 2;

                nextCtx.fillStyle = getBlockColor(getTetrominoTypeNumber(piece.type));

                for (let row = 0; row &lt; 4; row++) {
                    for (let col = 0; col &lt; 4; col++) {
                        if (piece.shape&#91;row] &amp;&amp; piece.shape&#91;row]&#91;col]) {
                            nextCtx.fillRect(
                                offsetX + col * cellSize + 1,
                                offsetY + row * cellSize + 1,
                                cellSize - 2,
                                cellSize - 2
                            );
                        }
                    }
                }
            }
        }

        function getBlockColor(typeNum) {
            const colors = {
                1: '#00ffff', // I - シアン
                2: '#ffff00', // O - 黄色
                3: '#800080', // T - 紫
                4: '#00ff00', // S - 緑
                5: '#ff0000', // Z - 赤
                6: '#0000ff', // J - 青
                7: '#ffa500'  // L - オレンジ
            };
            return colors&#91;typeNum] || '#666';
        }

        function getTetrominoTypeNumber(type) {
            const typeMap = { 'I': 1, 'O': 2, 'T': 3, 'S': 4, 'Z': 5, 'J': 6, 'L': 7 };
            return typeMap&#91;type] || 1;
        }

        function updateButtonStates(gameRunning) {
            elements.startBtn.disabled = gameRunning;
            elements.pauseBtn.disabled = !gameRunning || (gameState &amp;&amp; gameState.isGameOver);

            if (gameState &amp;&amp; gameState.isPaused) {
                elements.pauseBtn.textContent = '▶️ 再開';
            } else {
                elements.pauseBtn.textContent = '⏸️ 一時停止';
            }
        }

        function showStatusMessage(message, type = 'info') {
            elements.statusMessage.textContent = message;
            elements.statusMessage.className = `status-message status-${type}`;
            elements.statusMessage.style.display = 'block';

            setTimeout(() =&gt; {
                elements.statusMessage.style.display = 'none';
            }, 3000);
        }

        // ページが閉じられる時の処理
        window.addEventListener('beforeunload', () =&gt; {
            stopAutoDropSystem();
        });

        console.log('✅ スクリプト読み込み完了');
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code>

実行

これでテトリスのゲームが完成しました。
実行して実際にゲームが出来るか試してみましょう!!
実行してみるとウェブブラウザが立ち上がりテトリスの画面が出てきます。
実際にプレイしてみると問題なくテトリスで遊ぶことが出来ました。
ちなみに一番上までブロックが行くとゲームオーバーとなり、画像のような表記が出てスコアが表示されます。

まとめ

今回はテトリスを作成してみました。
記載出来ていませんが、途中では実行してもエラーがでてなかなか原因が分からず、Claudeに聞いて修正してもらったり、
修正してもらっても、さらに別のエラーが出たりとなかなか完成せずに苦労しました。
しかし、何とか完成までこぎつけられたので良かったと思います。
皆さんも是非機会があれば作成してみてはいかがでしょうか。