递归循环以检查条件是否良好,或重试

时间:2019-01-24 09:15:39

标签: javascript loops object recursion canvas

我必须在画布上生成几个对象。 问题是,如果我的条件(IF语句)有效,则不满足条件就不会再次循环。 所以有时候我只有1个玩家,而不是2个,等等。

设置棋子的功能是setPiece(),根据对象(障碍物,武器,玩家)的不同条件。 每个对象都有自己的调用setPiece的函数:setObstacles,setWeapons,setPlayers。

我已经尝试过在“其他”之后调用这些函数,因此setPiece再次循环。但这会导致控制台中出现堆栈错误,循环过多。

我还尝试了同时循环,但是没有成功实现,因此它也是一个无限循环。

<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-compatible" content="IE-edge">
<meta name="viewport" content="width=device-width, initial-scale-1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.css">
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

  <title>Lava Temple</title>

<style>
* {
  padding: 0;
  border: 0;
}

body{
  background-color: #181818;
}

#board {
  display: block;
  background-color: white;
  margin: 0 auto;
  margin-top: 100px;
}
</style>

</head>
<body>
    <canvas id="board" width="800" height="800"></canvas>

<script>

// BOARD OBJECT

function Board(width, height) {
    this.width = width;
    this.height = height;
    this.chartBoard = [];

    // Création du plateau logique
    for (var i = 0; i < this.width; i++) {
        const row = [];
        this.chartBoard.push(row);
        for (var j = 0; j < this.height; j++) {
            const col = {};
            row.push(col);
        }
    }
}

let board = new Board(10, 10);
console.log(board);

const ctx = $('#board').get(0).getContext('2d');

Board.prototype.drawBoard = function () {
    for (var i = 0; i < this.width; i++) {
        for (var j = 0; j < this.height; j++) {
            ctx.beginPath();
            ctx.strokeStyle = 'black';
            ctx.strokeRect(j * 64, i * 64, 64, 64);
            ctx.closePath();
        }
    }
};
board.drawBoard();



// OBJECTS OF THE GAME

function Obstacle(name, sprite) {
    this.name = name;
    this.sprite = sprite;
}
const lava = new Obstacle("Lave", "assets/lave.png");
const lava1 = new Obstacle("Lave1", "assets/lave.png");
const lava2 = new Obstacle("Lave2", "assets/lave.png");
const lava3 = new Obstacle("Lave3", "assets/lave.png");
const lava4 = new Obstacle("Lave4", "assets/lave.png");
const lava5 = new Obstacle("Lave5", "assets/lave.png");
const lava6 = new Obstacle("Lave6", "assets/lave.png");
const lava7 = new Obstacle("Lave7", "assets/lave.png");
const lava8 = new Obstacle("Lave8", "assets/lave.png");
const lava9 = new Obstacle("Lave9", "assets/lave.png");
const lavaArray = [lava, lava1, lava2, lava3, lava4, lava5, lava6, lava7, lava8, lava9];


function Weapon(name, sprite, damage) {
    this.name = name;
    this.sprite = sprite;
    this.damage = damage;
}
const dagger = new Weapon("Dague", "assets/dague.png", 5);
const sword = new Weapon("Epée", "assets/epee.png", 10);
const axe = new Weapon("Hache", "assets/hache.png", 15);
const flail = new Weapon("Fléau", "assets/fleau.png", 20);
const weaponArray = [dagger, sword, axe, flail];


function Player(name, sprite, life) {
    this.name = name;
    this.sprite = sprite;
    this.life = life;
}
const player1 = new Player("Joueur 1", "assets/joueur1.png", 100);
const player2 = new Player("Joueur 2", "assets/joueur2.png", 100);
const playerArray = [player1, player2];



// INIT OF THE GAME (code about my question)

Board.prototype.setPiece = function (piece) {

    let randomX = Math.floor(Math.random() * board.width);
    let randomY = Math.floor(Math.random() * board.height);

    let drawX = randomX * 64;
    let drawY = randomY * 64;


    if (randomX >= this.width || randomY >= this.height) {
        throw new Error('Pièce hors limite');
    }

    if (piece instanceof Obstacle) {

        if (!(this.chartBoard[randomY][randomX] instanceof Obstacle)) {
            this.chartBoard[randomY][randomX] = piece;
              ctx.fillRect(drawX, drawY,64,64);
        }

    } else if (piece instanceof Weapon) {

        if (!(this.chartBoard[randomY][randomX] instanceof Obstacle) && (!(this.chartBoard[randomY][randomX] instanceof Weapon))) {
            this.chartBoard[randomY][randomX] = piece;
            ctx.fillStyle = "red";
            ctx.fillRect(drawX, drawY,64,64);
        }

    } else if (piece instanceof Player) {

            if  (!(this.chartBoard[randomY][randomX] instanceof Obstacle) &&
                (!(this.chartBoard[randomY][randomX] instanceof Weapon) &&
                (!(this.chartBoard[randomY][randomX] instanceof Player) &&
                ((!(this.chartBoard[randomY][randomX + 1] instanceof Player)) || (typeof this.chartBoard[randomY][randomX + 1] === undefined)) &&
                ((!(this.chartBoard[randomY][randomX - 1] instanceof Player)) || (typeof this.chartBoard[randomY][randomX - 1] === undefined)) &&
                ((!(this.chartBoard[randomY + 1][randomX] instanceof Player)) || (typeof this.chartBoard[randomY + 1][randomX] === undefined)) &&
                ((!(this.chartBoard[randomY - 1][randomX] instanceof Player)) || (typeof this.chartBoard[randomY - 1][randomX] === undefined))))) {

                this.chartBoard[randomY][randomX] = piece;
                ctx.fillStyle = "blue";
                ctx.fillRect(drawX, drawY,64,64);
            }

    } else {
        throw new Error('Pièce non valide');
    }
};


Board.prototype.setObstacles = function () {
    for (let lava of lavaArray) {

        const obstacle = board.setPiece(lava);
    }
};
board.setObstacles();


Board.prototype.setWeapons = function () {
    let numWeapons = 4;
    let randomWeapon;
    let spawnWeapon;

    for (let i = 0; i < numWeapons; i++) {
        randomWeapon = Math.floor(Math.random() * weaponArray.length);
        spawnWeapon = board.setPiece(weaponArray[randomWeapon]);
    }
};
board.setWeapons();


Board.prototype.setPlayers = function () {

    for (let player of playerArray) {

        const spawnPlayer = board.setPiece(player);
    }
};
board.setPlayers();

</script>

</body>
</html>

实际结果:有时一切正常,但是有两个问题: -一块未放置在板上(画布)。 -播放器对象存在错误,因为IF条件(随机+或-x / y)试图检查棋盘长度之外,因此出现错误Undefined。不知道如何解决。

预期:了解如何在此画布上动态生成对象,以及如何在多个条件下重复循环。此外,还要学习如何实现画布的限制,以免出现未定义的错误。

1 个答案:

答案 0 :(得分:0)

我认为问题出在那些randomY增量和减量中的on超出界限。如果您在else if (piece instanceof Player) { ...之后立即console.log(randomY),那么看来只有在randomY为0或9的情况下,您只能获得一个玩家。

您可以尝试在else if (piece instanceof Player) { ...之后按照这些方式进行操作,这应该可以解决问题。

if (randomY === 0){
  randomY = randomY+1
}

if (randomY === 9){
  randomY = randomY-1
}

我不确定这是否仍被视为“随机”。瓷砖仍然可以占据边缘,因此机械师仍然感到“随机”。