将 p5js 与 javascript 一起使用,我的移动函数在发送字符串时有效,但在发送包含字符串的变量时无效

using p5js with javascript my function to move works when sent a string but not when sent a variable containing a string

使用名为 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])
}

谁能帮我解决这个问题?谢谢!! 编辑:如果其他人想使用这里的网络编辑器 link 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])
}