<!DOCTYPE html>
<html>
<head>
    <title>Simple Tetris Game</title>
    <style type="text/css">
        #tetris {
            position: relative;
            width: 400px;
            height: 600px;
            background: #000;
        }
<pre><code>    #tetris div {
        position: absolute;
        width: 20px;
        height: 20px;
        background: #ccc;
    }
&lt;/style&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    // This is the main logic for the game
    function tetris() {
        var i, j, rows, cols, squares;
        // Set up the board
        board = document.getElementById('tetris');
        rows = 15;
        cols = 10;
        squares = [];
        // Create the squares
        for (i = 0; i &lt; rows; i++) {
            for (j = 0; j &lt; cols; j++) {
                var square = document.createElement('div');
                square.style.top = i * 20 + 'px';
                square.style.left = j * 20 + 'px';
                board.appendChild(square);
                squares.push(square);
            }
        }
        // Create the pieces
        pieces = [
            [1, 1, 1, 1],
            [1, 1, 1, 0,
                1],
            [1, 1, 1, 0,
                0, 0, 1],
            [1, 1, 0, 0,
                1, 1],
            [1, 1, 0, 0,
                0, 1, 1],
            [0, 1, 1, 0,
                1, 1],
            [0, 1, 0, 0,
                1, 1, 1]
        ];
        // Draw the pieces
        currentPiece = randomPiece();
        draw();
        // Move the pieces
        function move(dir) {
            switch (dir) {
                case 'left':
                    currentPiece.x--;
                    break;
                case 'right':
                    currentPiece.x++;
                    break;
                case 'down':
                    currentPiece.y++;
                    break;
            }
        }
        // Draw the board
        function draw() {
            // Reset all of the squares on the board
            for (i = 0; i &lt; rows * cols; i++) {
                squares[i].style.background = '#000';
            }
            // Redraw the current piece
            for (i = 0; i &lt; currentPiece.layout.length; i++) {
                if (currentPiece.layout[i]) {
                    squares[currentPiece.y + Math.floor(i / 4) * cols + currentPiece.x + i % 4].style.background = '#ccc';
                }
            }
        }
        // Select a random piece
        function randomPiece() {
            var r = Math.floor(Math.random() * pieces.length);
            return {
                layout: pieces[r],
                x: Math.floor(cols / 2 - 2),
                y: 0
            };
        }
    }
&lt;/script&gt;
</code></pre>
</head>
<body onload="tetris()">
<pre><code>&lt;div id=&quot;tetris&quot;&gt;&lt;/div&gt;
</code></pre>
</body>
</html>

原文地址: https://www.cveoy.top/t/topic/lmpc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录