Как убедиться, что еда не помещается в змею?

Вам просто нужно запустить свой код после инициализации весны.

Если вы используете Spring-Boot, создайте новый компонент, который реализует ApplicationListener и запускает ваш код внутри метода onApplicationEvent.

Пример

@Component
public class ApplicationListenerBean implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        ConfigUtil.getVal("A");
    }
}

Однако, если вы хотите сделать ConfigUtil также в качестве пружинного компонента, вам нужно избавиться от статического блока инициализации и используйте вместо этого @PostConstruct аннотацию для вашего метода init.

Пример

@Component
@DependsOn("springContextUtil")
public class ConfigUtil {

    private String env;

    @PostConstruct
    private void init() {
        env = SpringContextUtil.getActiveProfile();
    }


    public static void getVal(String key) {
        System.out.print("Hello");
    }
}

0
задан lolz 19 January 2019 в 22:42
поделиться

2 ответа

объявляют функцию, которая генерирует случайную точку для еды, как это

function getFood() {
  // get a random point
  let food = {
    x : Math.floor(Math.random()*((cvsW/unit)-1)+1)*unit,
    y : Math.floor(Math.random()*((cvsH/unit)-1)+1)*unit
  }
  // check if this point is in the snake
  // loop through each point of the snake
  for(let i = 0; i < snake.length; i++) {
    // check if the current snake point equals the generated point
    if(snake[i].x == point.x && snake[i].y == point.x)
      // stop the loop and return getFood() to generate an other point
      return getFood()
  }
  return food
}

, и просто вызываем getFood () всякий раз, когда вы хотите получить позицию еды, которая не находится внутри змеи

[111 ]
0
ответ дан Oudmane 19 January 2019 в 22:42
поделиться

Вы можете .map текущие координаты змеи в массив строк currentSnakeX_Ys (x#_y#), затем сгенерировать food x и y с, а currentSnakeX_Ys.includes(`${food.x}_${food.y}`):

//create new food position
const currentSnakeX_Ys = snake.map(({ x, y }) => `${x}_${y}`);
do {
  food = {
    x: Math.floor(Math.random() * ((cvsW / unit) - 1) + 1) * unit,
    y: Math.floor(Math.random() * ((cvsH / unit) - 1) + 1) * unit
  }
} while (currentSnakeX_Ys.includes(`${food.x}_${food.y}`));

const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');

//set canvas dimension equal to css dimension
canvas.width = 768;
canvas.height = 512;

//now put those dimensions into variables
const cvsW = canvas.width;
const cvsH = canvas.height;

//create snake unit
const unit = 16;

//create snake array
let snake = [{
  x: cvsW / 2,
  y: cvsH / 2
}];

//delcare global variable to hold users direction
let direction;

//create food object
let food = {
  x: Math.floor(Math.random() * ((cvsW / unit) - 1) + 1) * unit,
  y: Math.floor(Math.random() * ((cvsH / unit) - 1) + 1) * unit
}

//read user's direction
document.addEventListener('keydown', changeDirection);

function changeDirection(e) {
  //set direction
  if (e.keyCode == 37 && direction != 'right') direction = 'left';
  else if (e.keyCode == 38 && direction != 'down') direction = 'up';
  else if (e.keyCode == 39 && direction != 'left') direction = 'right';
  else if (e.keyCode == 40 && direction != 'up') direction = 'down';
}

function draw() {
  //refresh canvas
  ctx.clearRect(0, 0, cvsW, cvsH);
  //draw snake
  for (let i = 0; i < snake.length; i++) {
    ctx.fillStyle = 'limegreen';
    ctx.fillRect(snake[i].x, snake[i].y, unit, unit);
  }

  //grab head position
  let headX = snake[0].x;
  let headY = snake[0].y;

  //posistion food on board
  ctx.fillStyle = 'red';
  ctx.fillRect(food.x, food.y, unit, unit);

  //send the snake in chosen direction
  if (direction == 'left') headX -= unit;
  else if (direction == 'up') headY -= unit;
  else if (direction == 'right') headX += unit;
  else if (direction == 'down') headY += unit;

  // //check if snake hit wall
  // if(headX < 0 || headY < 0 || headX > (cvsW-unit) || headY > (cvsH-unit)) {
  // 	clearInterval(runGame);
  // }

  if (headX < 0) headX = cvsW - unit;
  else if (headX > cvsW - unit) headX = 0;
  else if (headY < 0) headY = cvsH - unit;
  else if (headY > cvsH - unit) headY = 0;

  // check to see if snake has collided with itself
  // for(let i = 0; i < snake.length; i++) {
  // 	if(headX == snake[i].x && headY == snake[i].y) {
  // 		clearInterval(game);
  // 	}
  // }

  //create new head
  let newHead = {
    x: headX,
    y: headY
  }

  //if snake eats food -do this
  if (headX == food.x && headY == food.y) {
    //create new food position
    const currentSnakeX_Ys = snake.map(({ x, y }) => `${x}_${y}`);
    do {
      food = {
        x: Math.floor(Math.random() * ((cvsW / unit) - 1) + 1) * unit,
        y: Math.floor(Math.random() * ((cvsH / unit) - 1) + 1) * unit
      }
    } while (currentSnakeX_Ys.includes(`${food.x}_${food.y}`));

    //add 3 units to the snake
    for (let i = 30; i > 0; i--) {
      snake.unshift(newHead);
    }
  } else {
    //remove tail
    snake.pop();
  }

  //add head to snake
  snake.unshift(newHead);
}

//run game engine
let runGame = setInterval(draw, 40);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Snake Game</title>
  <style>
    body {
      background-color: #333;
    }
    
    canvas {
      background-color: #4d4d4d;
      margin: auto;
      display: block;
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      width: 750px;
      height: 500px;
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>
  <script src="script.js"></script>
</body>

</html>

(вы также можете проходить итерации по snake вместо каждого поколения продуктов питания и проверять текущий x ] и y не относятся как к x, так и к y пищи, но заранее создав массив строк, все становится намного проще, потому что тогда вы можете просто использовать тест .includes)

код СУХОЙ, вместо того, чтобы вводить его каждый раз, когда вам нужно сгенерировать пищу, поместите вышеупомянутое в функцию и вызовите эту функцию:

0
ответ дан CertainPerformance 19 January 2019 в 22:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: