C
C
CrystaZZ2019-03-17 18:42:53
JavaScript
CrystaZZ, 2019-03-17 18:42:53

I want to make it so that when you click on the apple, it disappears and adds score++ click array canvas onclick?

Dear programmers. Help me please) I want to make it so that when you click on the apple, it disappears and adds a score ++
(click) should work exactly when you click on the apple, that is, the "apple"
game code:

spoiler
window.stopgame = false;

var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");

var fonimg = new Image();
fonimg.src = "img/bg.jpg";

var push = new Image();

push.src = "img/push.gif";

var score = 0;
var second = 30;

//Privilegie

let coin = 1000;

var buyelexir = 0;

var tims = second;


var gap = 273;
var gapbig = 273;

var self = false;

var username = document.getElementById("nameplayer").value;

var result = second + score;

//Start podvodnyi_mir music :)

let podvodnyi_mir = new Audio();
podvodnyi_mir.src = "audio/podvodnyi_mir.mp3"

let speed = {x:0, y:300,dx:1,dy:2};

var x=10;

//Маленькая рыбка

function getMouesPosition(e) {
    var mouseX = e.offsetX * cvs.width / cvs.clientWidth | 0;
    var mouseY = e.offsetY * cvs.height / cvs.clientHeight | 0;
    return {x: mouseX, y: mouseY};
}

function killFoodbig(f) {
  var pos = fish.indexOf(f);
  if (pos === -1) {
    return;
  }
  fish.splice(pos, 1);
  score += 20;
}

function foodbig(e){
  let mouse = getMouesPosition(e);
  fish.forEach(f => {
  	if (mouse.x > f.x && mouse.y > f.y && mouse.x < f.x + fishsmall.width && mouse.y < f.y + fishsmall.height) {
    	killFoodbig(f);
    }
  });
}
cvs.addEventListener("click", foodbig);
//Средняя рыбка


cvs.addEventListener("click", food);

function killFood(f) {
  let pos = fishbigg.indexOf(f);
  if (pos === -1) {
    return;
  }
  fishbigg.splice(pos, 1);
  score += 40;
}

function food(e){
  let mouse = getMouesPosition(e);
  fishbigg.forEach(f => {
  	if (mouse.x > f.x && mouse.y > f.y && mouse.x < f.x + fishbig.width && mouse.y < f.y + fishbig.height) {
    	killFood(f);
    }
  });
}

let fish = [];

fish[0] = {
  x : cvs.width,
  y : 650
}

let fishbigg = [];
fishbigg[0] = {
  x : cvs.width - cvs.width,
  y : 450
},

fishbigg[1] = {
  x : 732,
  y : 950
}



if(window.stopgame)fonimg.onload = function (){
  game();
}

function game(){
if(!window.stopgame)render();
requestAnimationFrame(game);
}


function render(){
//FON
  ctx.drawImage(fonimg, 0, 0, );
//Физика


 for(var i = 0; i < fish.length; i++){
     ctx.drawImage(fishsmall, fish[i].x, fish[i].y);
     
     
      fish[i].x-= 2;
     
     if(fish[i].x === cvs.width - 550){
        fish.push({
           x : cvs.width,
           y : ~~(Math.random() * fishsmall.height - fishsmall.height + gapbig)
          })
      
    }
    
    if(fish.length <= 1){
      fish.push({
           x : cvs.width + gap,
           y : ~~Math.floor(Math.random() * fishsmall.height - fishsmall.height + gapbig)
          })
    }
    
    
 }
 
//Средняя рыбка

 for(let i = 0; i < fishbigg.length; i++){
     ctx.drawImage(fishbig, fishbigg[i].x, fishbigg[i].y);
     		
    fishbigg[i].x+= 2;
    
    if(fishbigg[i].x == cvs.width - 1830){
      fishbigg.push({
        x : cvs.width - 2150,
        y : cvs.height - ~~(Math.random() * cvs.height)
      })
      
 } }
 
  switch(fish){
  case 0:
          fishbigg.push({
        x : cvs.width,
        y : 0
      })
      break;
}
  
  document.getElementById("score").innerHTML = (score);
  document.getElementById("coin").innerHTML = (coin);
  document.getElementById("tiktak").style.display = "block";
  document.getElementById("scores").style.display = "block";
   

document.getElementById("nameinfo").style.display = "block";
document.getElementById("leaderboard").style.display = "block";
document.getElementById("leaderboard-fon").style.display = "block";
document.getElementById("pausegame").style.display = "block";
document.getElementById("top-block").style.display = "block";
document.getElementById("bottom-block-elixir").style.display = "block";
}

//Start Game
function startgame(){

   document.getElementById("content").style.display = "none";
   game() <= false;
   timer() <= false;
  
}

//Value Input + name
window.value = function (value){
  document.getElementById("nameinfo").innerHTML = (value);
  document.getElementById("result-name").innerHTML = (value);
  console.log(value);
}

//Кнопка пауза
function pause(){
  window.stopgame = !window.stopgame;
}

//Покупка Элексира
window.byelexir = function (t){
  coin-= 50;
  document.getElementById("elexir-time").innerHTML = (buyelexir)
  buyelexir+=1;
  coin > 0 ? coin-- : coin = 0;
  
  if(coin == 0){
    
    buyelexir--;
    
  }
     
  if(coin == 0)return error_coins();
}

//Рспользовать Элексир
function elexir_time_take(){
  document.getElementById("elexir-time").innerHTML = (buyelexir)
  buyelexir--;
  
  if(buyelexir < 0){
    buyelexir = 0;
}
  
    if(buyelexir > 0)return second+= 30;
  
  if(buyelexir <= 0){
    error_elexir();
  }
  else{
    alert('Ошибка')
  }
     
    	 

}


//Увдомление об ошибке
function error_coins(str) {
        $('#error_message').html(str);
        $("#error_box").fadeIn(500).delay(3000).fadeOut(500);
    $("#error_coins").fadeIn(500).delay(3000).fadeOut(500);
}

function error_elexir(str) {
        $('#error_message').html(str);
    $("#error_elexir").fadeIn(500).delay(3000).fadeOut(500);
}

failed to do :(
Help Me :)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Proskurin, 2019-03-17
@CrystaZZ

When you click on the canvas, you need to check that you clicked on the area of ​​one of the apples. To do this, on each click, for each apple, check that mouseX > apple.x and mouseX < apple.x + apple.width, and also for Y - mouseY > apple.y and mouseY < apple.y + apple.height
UPD : look. First, we need to get the mouse coordinates, but we can’t just extract the mouse coordinates from the mousemove event object, we need to do some manipulations.
1) Assign the mousemove event not to the window, but directly to the canvas itself, so you can get the mouse coordinates relative to the canvas and not the window.
2) Your canvas expands to full screen via css, which means that the coordinate system is stretched, from which, for example, by clicking on the point {10, 10} with the canvas doubled, the coordinate will be {5, 5}. Therefore, you need to either change the width of the canvas through JS to the width attribute, or use this function

function getMouesPosition(e) {
    var mouseX = e.offsetX * cvs.width / cvs.clientWidth | 0;
    var mouseY = e.offsetY * cvs.height / cvs.clientHeight | 0;
    return {x: mouseX, y: mouseY};
}

you need to pass the mousemove event object to it. It will get the coordinates of the point where the mouse clicked in the internal coordinate system.
Now we can rewrite the food method like this
// Этот метод удаляет нужный фрукт из списка, а также, добавляет очки. 
function killFood(f) {
  let pos = fruit.indexOf(f);
  if (pos === -1) {
  	// already dead
    return;
  }
  fruit.splice(pos, 1);
  score += ~~Math.floor(Math.random()+ 17)
}

function food(e){
  let mouse = getMouesPosition(e); // Получаем координаты мыши
  // Пройдемся по каждому фрукту. Использую forEach, но вы можете и обычный for, только не забывайте обновить переменную индекса
  fruit.forEach(f => {
    if (mouse.x > f.x && mouse.y > f.y && mouse.x < f.x + apple.width && mouse.y < f.y + apple.height) {
      killFood(f); // Удаляем фрукт
    }
  });
}

Working example https://jsfiddle.net/hzbxm5nk/

A
Antony Bark, 2016-12-01
@tolfy

It seems to me that this is an adaptation based on the Futura family.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question