用 p5.js 制作俄罗斯方块
Making Tetris with p5.js
到目前为止我有一些代码:
function setup() {
createCanvas(500,550);
}
function draw() {
background(150);
o();
}
function block(x,y) {
rectMode(CENTER)
rect(x,y, cols, rows, 2)
}
function o() {
fill(255, 255,0)
block(width/2, rows);
block(width/2, rows* 2);
block(width/2 + cols, cols)
block(width/2 + cols, cols * 2)
}
我想知道下一步该怎么做。我想创建 drop
函数,这就是它的样子:
function drop() {
rows += rows;
cols += cols;
}
然后将其添加到 setup
函数中:
frameRate(10);
所以它移动得更慢,但那是行不通的。
我不知道如何在不更改 cols
和 rows
的值的情况下使块下降。我的问题是,如何让方块在一个函数中向下移动(例如,一个名为 drop
的函数)?
编辑:drop 函数不会起作用,因为它会改变大小,而不是位置。
要移动方块,它需要有一个 x
和一个 y
位置。
目前,您只是硬编码了位置。
block(width/2, rows);
相反,你应该这样做
let x;
let y = rows;
function setup() {
createCanvas(500, 500);
x = width / 2; //you could not set x before now, because the program didn't yet know what the width was
然后,将您的 o()
函数替换为:
function o() {
fill(255, 255,0)
block(x, y);
block(x, y + cols);
block(x + cols, y);
block(x + cols, y + cols);
}
最后,您可以在 drop()
函数中更改 x 和 y 的位置(别忘了实际调用它)
function drop() {
y += 10;
}
到目前为止我有一些代码:
function setup() {
createCanvas(500,550);
}
function draw() {
background(150);
o();
}
function block(x,y) {
rectMode(CENTER)
rect(x,y, cols, rows, 2)
}
function o() {
fill(255, 255,0)
block(width/2, rows);
block(width/2, rows* 2);
block(width/2 + cols, cols)
block(width/2 + cols, cols * 2)
}
我想知道下一步该怎么做。我想创建 drop
函数,这就是它的样子:
function drop() {
rows += rows;
cols += cols;
}
然后将其添加到 setup
函数中:
frameRate(10);
所以它移动得更慢,但那是行不通的。
我不知道如何在不更改 cols
和 rows
的值的情况下使块下降。我的问题是,如何让方块在一个函数中向下移动(例如,一个名为 drop
的函数)?
编辑:drop 函数不会起作用,因为它会改变大小,而不是位置。
要移动方块,它需要有一个 x
和一个 y
位置。
目前,您只是硬编码了位置。
block(width/2, rows);
相反,你应该这样做
let x;
let y = rows;
function setup() {
createCanvas(500, 500);
x = width / 2; //you could not set x before now, because the program didn't yet know what the width was
然后,将您的 o()
函数替换为:
function o() {
fill(255, 255,0)
block(x, y);
block(x, y + cols);
block(x + cols, y);
block(x + cols, y + cols);
}
最后,您可以在 drop()
函数中更改 x 和 y 的位置(别忘了实际调用它)
function drop() {
y += 10;
}