我想在7x7网格中制作一个简单的游戏,我想从数组中放置点击图像,然后检查匹配(如连接四)
我有一个网格,所有的正方形在HTMLdiv中,像这样:
<div class="grid">
<div class="square" id="1"></div>
<div class="square" id="2"></div>
<...............................>
<div class="square" id="49"></div>
和一些存储在app.js数组中的图像:
document.addEventListener("DOMContentLoaded", () => {
const squares = document.querySelectorAll(".square")
const scoreDisplay = document.getElementById("result")
let score = 0;
squares[24].style.backgroundImage = "url('res/middle.png')"
const cards = [
{
name: 'blue',
img: 'res/blue.png'
},
{
name: 'yellow',
img: 'res/yellow.png'
},
{
name: 'red',
img: 'res/red.png'
},
{
name: 'orange',
img: 'res/orange.png'
},
{
name: 'green',
img: 'res/green.png'
},
{
name: 'pink',
img: 'res/pink.png'
},
{
name: 'ivory',
img: 'res/ivory.png'
},
]
数组的随机图像不会出现在网格上,但是分数更新并且没有控制台错误。
let randomCard = Math.floor(Math.random() * cards.length)
// clickedPosition = ?
squares.forEach(square => {
square.addEventListener('click', function(e) {
if(square.id !== squares[24] ) {
score ++;
scoreDisplay.textContent = score
e.target.style.backgroundImage = randomCard.img
} else {
}
})
})
})
我明白了!
将cards数组更改为如下所示:
const cards = ["url (res/blue.png)","url (res/yellow.png)","url (res/red.png)","url (res/orange.png)","url (res/green.png)","url (res/pink.png)","url("res/ivory.png")";)
,现在一个单一的图像将出现在点击(不幸的是不是随机的,但这是一个进步!)
e.target.style.backgroundImage = cards[randomCard]