I'm trying to write tetris in JS with matrixes instead of sprites.
(我试图用矩阵而不是精灵在JS中编写俄罗斯方块。)
Basically to be better at visualising 2d arrays.(基本上是要更好地可视化二维数组。)
I rotate a block by transposing its matrix data and then reversing the rows.
(我通过转置块的矩阵数据然后反转行来旋转块。)
But because the block's width and height doesn't completely fill this 4x4 matrix the rotating results in the block moving, instead of rotating in place.(但是,由于块的宽度和高度不能完全填充此4x4矩阵,因此旋转会导致块移动,而不是原地旋转。)
I can't see it, i've already spent more than two days with trying to get such a simple game as tetris working, restarting from scratch a couple of times.. I need help, i really want to be able to program games, and the only thing i got working was tic tac toe.
(我看不到,我已经花了超过两天的时间尝试让tetris这样简单的游戏正常工作,从头开始重新启动了几次。.我需要帮助,我真的很想能够编写游戏程序,而我唯一要做的就是井字游戏。)
Which i spent more time on than i should.(我花了比我更多的时间。)
Here's the full js code.
(这是完整的js代码。)
Clicking the canvas rotates the piece.(单击画布将旋转作品。)
var canvas = document.getElementById('c'); var ctx = canvas.getContext('2d'); canvas.width = 400; canvas.height = 600; // game object var G = {}; var current = 0; var x = 0; var y = 0; //GRID G.grid = []; G.gridColumns = 10; G.gridRows = 15; for (var i = 0; i < G.gridColumns; i++) { G.grid[i] = []; for (var j = 0; j < G.gridRows; j++) { G.grid[i][j] = 0; } } // Array with all different blocks G.blocks = []; //block constructor function block() {}; G.blocks[0] = new block(); G.blocks[0].matrix = [ [1, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0] ]; G.blocks[0].width = 2; G.blocks[0].height = 3; function transpose(m) { // dont understand this completely, but works because j<i for (var i = 0; i < m.matrix.length; i++) { for (var j = 0; j < i; j++) { var temp = m.matrix[i][j]; m.matrix[i][j] = m.matrix[j][i]; m.matrix[j][i] = temp; } } } function reverseRows(m) { for (var i = 0; i < m.matrix.length; i++) { m.matrix[i].reverse(); } } function rotate(m) { transpose(m); reverseRows(m); } function add(m1, m2) { for (var i = 0; i < m1.matrix.length; i++) { for (var j = 0; j < m1.matrix[i].length; j++) { m2[i + x][j + y] = m1.matrix[i][j]; } } } function draw(matrix) { for (var i = 0; i < matrix.length; i++) { for (var j = 0; j < matrix[i].length; j++) { if (matrix[i][j] === 1) { ctx.fillRect(j * 20, i * 20, 19, 19); } } } ctx.strokeRect(0, 0, G.gridColumns * 20, G.gridRows * 20); } window.addEventListener("click", function(e) { rotate(G.blocks[current]); }); function tick() { ctx.clearRect(0, 0, canvas.width, canvas.height); add(G.blocks[current], G.grid); draw(G.grid); } setInterval(tick, 1000 / 30);
<canvas id="c"></canvas>
Please ignore the little quirks in my code, i learned programming by myself.
(请忽略我代码中的一些小问题,因为我是自己学习编程的。)
Thanks in advance :)(提前致谢 :))
ask by onlyme0349 translate from so