水果消消乐
介绍
消消乐是一款益智类休闲游戏,在排队等待做核酸的时候可以打开手机玩一会,陪你度过这漫长且无聊的等待期。
本题需要实现一款水果消消乐的游戏,在 4 X 4 的格子上,消除相同的水果得两分,否则扣两分,考验一下大家的记忆力,看看最后谁的分数最多。
准备
开始答题前,需要先打开本题的项目代码文件夹,目录结构如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| ├── css │ └── style.css ├── images │ ├── apple.png │ ├── cherry.png │ ├── grape.png │ ├── peach.png │ ├── pear.png │ ├── strawberry.png │ ├── tangerine.png │ └── watermelon.png ├── js │ ├── index.js │ └── jquery-3.6.0.min.js ├── effect.gif └── index.html
|
其中:
css/style.css 是样式文件。
images 是图片文件夹。
js/index.js 是实现游戏功能的 js 文件。
js/jquery-3.6.0.min.js 是 jQuery 文件。
effect.gif 是最终实现的效果动图。
index.html 是主页面。
注意:打开环境后发现缺少项目代码,请手动键入下述命令进行下载:
1 2
| cd /home/project wget https://labfile.oss.aliyuncs.com/courses/9788/03.zip && unzip 03.zip && rm 03.zip
|
在浏览器中预览 index.html 页面,点击开始按钮不能正常进行游戏,效果如下:

目标
请完善 js/index.js 文件。
完成后的效果见文件夹下面的 gif 图,图片名称为 effect.gif(提示:可以通过 VS Code 或者浏览器预览 gif 图片)。
具体说明如下:
- 点击开始按钮后,该按钮被隐藏,方格上的图片显示后又隐藏。
- 点击方格,方格中的图片显示,页面显示两张图片后,比较图片是否相同。
- 如果图片上的水果相同,方格即可消除,并得 2 分;如果图片上的水果不相同,图片隐藏,并扣 2 分(分数可以为负数)。
- 在文本 “当前分数为:” 的冒号后面会实时统计当前的得分情况。
规定
- 请勿修改
js/index.js 文件外的任何内容。
- 请严格按照考试步骤操作,切勿修改考试默认提供项目中的文件名称、文件夹路径、class 名、id 名、图片名等,以免造成无法判题通过。
判分标准
总通过次数: 864 | 总提交次数: 904 | 通过率: 95.6%
难度: 中等 标签: 2022, 国赛, Web 前端, JavaScript
题解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| const startBtn = document.getElementById('start') const imgs = document.querySelectorAll('img') const imgBoxs = document.querySelectorAll('.img-box') let matchArr = []
function startGame() { startBtn.style.display = 'none' imgs.forEach(item => { item.style.display = 'block' }) setTimeout(() => { imgs.forEach(item => { item.style.display = 'none' }) }, 1000)
imgBoxs.forEach(item => { item.addEventListener('click', () => { console.log(item.childNodes); item.childNodes[1].style.display = 'block' matchArr.push(item) if (matchArr.length === 2) { if (matchArr[0].childNodes[1].alt === matchArr[1].childNodes[1].alt) { matchArr[0].style.visibility = 'hidden' matchArr[1].style.visibility = 'hidden' handleScore(2) } else { matchArr[0].childNodes[1].style.display = 'none' matchArr[1].childNodes[1].style.display = 'none' handleScore(-2) } matchArr = [] } }) }) }
function handleScore(val) { const scoreInput = document.getElementById('score') scoreInput.innerText = (parseInt(scoreInput.innerText) + val).toString() }
|