Как реализовать счетчик кликов / счетчик только с JS (если это возможно)? - PullRequest
1 голос
/ 23 мая 2019

Я пытаюсь завершить основную структуру создаваемой мной компьютерной игры и пытаюсь внедрить в нее «оценки» или значения, чтобы сделать ее более функциональной.

У меня есть базовый код, который на самом деле работает, но не совсем так, как я хочу.

Вот код, который я использовал (все переменные были объявлены)

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 600;
        this.canvas.height = 480;
        //this.canvas.style.cursor = "none"; //hide the original cursor
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 1);
        window.addEventListener('mousedown', function (e) {
            myGameArea.x = e.pageX;
            myGameArea.y = e.pageY;
            console.log("hello");
        });
        window.addEventListener('mouseup', function (e) {
            myGameArea.x = false;
            myGameArea.y = false;
        });
    }, 
    clear : function(){
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}
function component(width, height, color, x, y, type) {
    this.type = type;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;    
    this.x = x;
    this.y = y;    
    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);

        } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }

    }
    this.clicked = function() {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var clicked = true;
        if ((mybottom < myGameArea.y) || (mytop > myGameArea.y) || (myright < myGameArea.x) || (myleft > myGameArea.x)) {
          clicked = false;
        }
        return clicked;
      }
}

function updateGameArea() {
    myGameArea.clear();
    if (myGameArea.x && myGameArea.y) {
        if (item1.clicked()) {
            console.log("red square says hi");
            myScore = myScore + 1;
        }
        if (item2.clicked()) {
            console.log("orange square says hi");
        }
        if (item3.clicked()) {
            console.log("yellow square says hi");
        }
        if (item4.clicked()) {
            console.log("green square says hi");
        }
        if (item5.clicked()) {
            console.log("blue square says hi");
        }
        if (item6.clicked()) {
            console.log("purple square says hi");
        }      
    }

    scoreDisplay.text = "Score: " + myScore;
    scoreDisplay.update();
    myGamePiece.update();
    item1.update();
    item2.update();
    item3.update();
    item4.update();
    item5.update();
    item6.update();
    itemArea.update();
    orderScreen.update();
}

Когда я щелкаю по красному квадрату (пункт 1), счет увеличивается, но он не останавливается, пока я не перестаю щелкать или моя мышь не работает. Я хочу, чтобы мой код просто увеличивал значение один раз за клик объекта, а не увеличивал его, когда мышь нажата.

Ответы [ 2 ]

0 голосов
/ 23 мая 2019

Используйте прослушиватель событий, как вы сделали для событий mousedown и mouseup:

Это будет захватывать каждый клик внутри холста, а не снаружи.

Определите переменную в вашем myGameArea объекте:

var myGameArea = {
    canvas : document.createElement("canvas"),
    clicks : 0, //HERE
    start : function() {
        this.canvas.width = 600;
        this.canvas.height = 480;
    ...

Затем добавьте прослушиватель событий в функцию start() :

var myGameArea = {
    canvas : document.createElement("canvas"),
    clicks : 0,
    start : function() {
        this.canvas.width = 600;
        this.canvas.height = 480;
        //this.canvas.style.cursor = "none"; //hide the original cursor
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 1);
        window.addEventListener('mousedown', function (e) {
            myGameArea.x = e.pageX;
            myGameArea.y = e.pageY;
            console.log("hello");
        });

        this.canvas.addEventListener("click",(e)=>{ // Use ES6 arrow function
          this.clicks++;
        });

    ...

Взгляните на пример:

var myGameArea = {
    canvas : document.querySelector("canvas"),
    clicks : 0,
    start : function(){
       this.canvas.addEventListener("click",(e)=>{ // Use ES6 arrow function
          this.clicks++;
          console.log(`Click+1, now = ${this.clicks}`);
       });
    }
};

myGameArea.start();
canvas{
  background: black;
}
<canvas width="300" height="300"></canvas>
0 голосов
/ 23 мая 2019

Логика того, что вы хотите, заключается в следующем:

JavaScript:

var i = 0;
    function addPoint() {
        if (document.getElementById("value").value != null) {
            document.getElementById("value").value = ++i;
        } else { return false }
    }

HTML:

<button onclick="addPoint()">+1 Point</button>
<input type="text" id="value" value="0"></input>

Если вы хотите больше "завершить "подход, вы можете сделать это в части JavaScript:

function addPoint() {
    var addValue = parseInt(document.getElementById("value").value, 10);
    addValue = isNaN(addValue) ? 0 : addValue;
    addValue++;
    document.getElementById("value").value = addValue;
}
...