我创建了一个简单的“打地鼠”游戏,其中同一图像在游戏空间中随机且随机地出现在游戏空间中,如果您单击该图像,该图像就会消失,这没有问题。为了使游戏更加困难,我添加了图像映射,因此您必须单击图像的特定部分,现在我不知道如何在单击后删除关联的图像。我已经在该站点上阅读了许多相关问题,而我发现的最接近问题是the answer by FiLeVeR10 that used hover,但是它太慢了,只能在大约20%的速度下快速玩游戏。
最有效的另一种方法是在图像地图区域中添加一个.on点击。此方法可以很好地运行我的IncrementScore()函数,但是我可以在下一行使用什么来删除关联的图像?我已经尝试了至少一百种不同的方法,但是它们都不起作用。向该区域添加onclick属性的行为相同,并且会增加分数,但是删除底层图像仍然遇到相同的问题。
我什至只能看到图像的位置是offsetParent,但是游戏空间中的所有图像也都在其中,而不仅仅是我要删除的图像,所以我不知道该如何选择正确的那一个。在阅读了一些相关问题的答案之后,我开始认为它不能足够快地完成游戏,而我花了数小时徒劳地尝试不同的事情只会增加我的怀疑,但是我在这里创建了一个帐户并且我将发布我的第一个问题,以明确确定它是否可以完成。相关代码如下。谢谢。
$(document).ready(function() {
$('#molemap').on('click', function(e) {
incrementScore(); //This works perfectly
$(this).I.have.tried.hundreds.of.things.here; //And I can't figure it out
});
});
function addMole() {
$('#gamespace').append('<img src="img/simole.png" class="mole" usemap="#molemap" id="mole-image" style="left: ' + imgXPos + 'px; top: ' + imgYPos + 'px;" />');
}
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<div id="content">
<map name="molemap">
<area id="molemap" coords="25,163,56,139,48,125,44,108,45,92,8,82,4,100,5,118,9,133,15,146" shape="poly"/>
</map>
<div id="gamespace">
</div>
</div>
您需要为每个图像创建一个不同的地图,否则,您将无法确定单击了哪个图像。这会为该区域分配data-mole
属性,因此您可以在单击时将其与匹配的图像相关联:
<map name="mm1">
<area shape="rect" data-mole="1" coords="20, 20, 60, 60" href="#" />
</map>
<img id="mole1" src="your/mole/img.png" usemap="#mm1" style="left: 10px; top: 20px;" />
具有3个图像的工作示例。
// listen for clicks within the gamespace
const gameSpace = document.getElementById('gamespace');
gamespace.addEventListener('click', function(evt) {
// determine if click was within a mole's area
const iMole = evt.target.dataset.mole;
if (iMole) {
// alert(`you whacked mole ${iMole}`);
let moleImg = document.getElementById(`mole${iMole}`);
moleImg.remove();
} else {
alert('you missed!');
}
});
#gamespace {
background-color: green;
width: 400px;
height: 180px;
}
img {
height: 80px;
width: 80px;
position: absolute;
}
<div id="gamespace">
<map name="mm1">
<area shape="rect" data-mole="1"
coords="20, 20, 60, 60" href="#" />
</map>
<img id="mole1" src="https://picsum.photos/80/80" usemap="#mm1"
style="left: 10px; top: 20px;" />
<map name="mm2">
<area shape="rect" data-mole="2"
coords="20, 20, 60, 60" href="#" />
</map>
<img id="mole2" src="https://picsum.photos/80/80" usemap="#mm2"
style="left: 100px; top: 40px;" />
<map name="mm3">
<area shape="rect" data-mole="3"
coords="20, 20, 60, 60" href="#" />
</map>
<img id="mole3" src="https://picsum.photos/80/80" usemap="#mm3"
style="left: 200px; top: 18px;" />
</div>