使用被称为p5与javascript的库,我试图使游戏蛇,但它根本无法工作.正如标题中所描述的那样,只有当我给移动函数一个参数,如 "DOWN "时,它才会移动,但当我给它包含值 "DOWN "的变量方向时,它不会移动。
let fr = 5
function setup() {
frameRate(fr)
createCanvas(400, 400);
}
x1 = 201
y1 = 201
direction = "NONE"
function move(direction) {
if (direction === "UP") {
y1 = y1 - 20
}
else if (direction === "DOWN") {
y1 = y1 + 20
}
else if (direction === "LEFT") {
x1 = x1 - 20
}
else if (direction === "RIGHT") {
x1 = x1 + 20
}
}
function draw() {
let c = color('#1cb82e')
direction = "down"
background(0);
square(x1,y1,18);
fill(c);
move(direction);
}
function keyPressed() {
var validKeys = [37,38,39,40]
var dict = {
37:"LEFT",
38:"UP",
39:"RIGHT",
40:"DOWN"
}
if (validKeys.includes(keyCode) === true) {
direction = dict[keyCode];
}
print(dict[keyCode])
}
有谁能帮我解决这个问题吗,谢谢!!编辑:如果还有人想使用网络编辑器,这里是链接。https:/editor.p5js.org。
你可以使用你的全局 direction
变量,而不是在你的 move
职能。
let fr = 5
function setup() {
frameRate(fr)
createCanvas(400, 400);
}
x1 = 201
y1 = 201
direction = "NONE"
function move() {
if (direction === "UP") {
y1 = y1 - 20
}
else if (direction === "DOWN") {
y1 = y1 + 20
}
else if (direction === "LEFT") {
x1 = x1 - 20
}
else if (direction === "RIGHT") {
x1 = x1 + 20
}
}
function draw() {
let c = color('#1cb82e')
background(0);
square(x1,y1,18);
fill(c);
move();
}
function keyPressed() {
var validKeys = [37,38,39,40]
var dict = {
37:"LEFT",
38:"UP",
39:"RIGHT",
40:"DOWN"
}
if (validKeys.includes(keyCode) === true) {
direction = dict[keyCode];
}
print(dict[keyCode])
}