HTML+CSS+JS实现2048经典小游戏(附完整源码)

2024-06-05 18:20

本文主要是介绍HTML+CSS+JS实现2048经典小游戏(附完整源码),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

2048 小游戏的目标是通过合并数字单元格,最终在 4x4 的棋盘上创建一个值为 2048 的单元格。

一、预览效果

在这里插入图片描述

二、程序源码

html代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>2048 Game</title><link rel="stylesheet" href="game.css">
</head>
<body><div class="game-container"><div class="score-container">分数: <span id="score">0</span></div><div class="game-board" id="game-board"><!-- 这里将动态生成游戏单元格 --></div></div><script src="game.js"></script>
</body>
</html>

css代码

/* styles.css */
body {display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;background-color: #faf8ef;font-family: 'Arial', sans-serif;
}.game-container {display: flex;justify-content: center;align-items: center;flex-direction: column;
}.score-container {margin-bottom: 20px;font-size: 24px;font-weight: bold;color: #776e65;
}.game-board {display: grid;grid-template-columns: repeat(4, 100px);grid-template-rows: repeat(4, 100px);gap: 10px;background-color: #bbada0;padding: 10px;border-radius: 10px;
}.cell {width: 100px;height: 100px;display: flex;justify-content: center;align-items: center;background-color: #cdc1b4;border-radius: 5px;font-size: 24px;font-weight: bold;color: #776e65;
}.cell-2 { background-color: #eee4da; }
.cell-4 { background-color: #ede0c8; }
.cell-8 { background-color: #f2b179; color: #f9f6f2; }
.cell-16 { background-color: #f59563; color: #f9f6f2; }
.cell-32 { background-color: #f67c5f; color: #f9f6f2; }
.cell-64 { background-color: #f65e3b; color: #f9f6f2; }
.cell-128 { background-color: #edcf72; color: #f9f6f2; }
.cell-256 { background-color: #edcc61; color: #f9f6f2; }
.cell-512 { background-color: #edc850; color: #f9f6f2; }
.cell-1024 { background-color: #edc53f; color: #f9f6f2; }
.cell-2048 { background-color: #edc22e; color: #f9f6f2; }

js代码

// game.js
document.addEventListener('DOMContentLoaded', () => {const gameBoard = document.getElementById('game-board');const scoreElement = document.getElementById('score');const size = 4;let cells = [];let score = 0;function createBoard() {for (let i = 0; i < size * size; i++) {const cell = document.createElement('div');cell.classList.add('cell');gameBoard.appendChild(cell);cells.push(cell);}addNumber();addNumber();}function addNumber() {let emptyCells = cells.filter(cell => cell.innerText === '');if (emptyCells.length === 0) return;let randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];randomCell.innerText = Math.random() > 0.1 ? 2 : 4;randomCell.classList.add(`cell-${randomCell.innerText}`);}function move(direction) {let hasMoved = false;for (let i = 0; i < size; i++) {let rowOrCol = [];for (let j = 0; j < size; j++) {let index = direction === 'left' || direction === 'right' ? i * size + j : j * size + i;rowOrCol.push(cells[index]);}if (direction === 'right' || direction === 'down') rowOrCol.reverse();let newRowOrCol = slide(rowOrCol);if (direction === 'right' || direction === 'down') newRowOrCol.reverse();for (let j = 0; j < size; j++) {let index = direction === 'left' || direction === 'right' ? i * size + j : j * size + i;if (cells[index].innerText !== newRowOrCol[j].innerText) hasMoved = true;cells[index].innerText = newRowOrCol[j].innerText;cells[index].className = 'cell';if (cells[index].innerText !== '') cells[index].classList.add(`cell-${cells[index].innerText}`);}}if (hasMoved) {addNumber();updateScore();if (checkGameOver()) {setTimeout(() => alert('游戏结束!'), 100);}}}function slide(rowOrCol) {let arr = rowOrCol.filter(cell => cell.innerText !== '').map(cell => parseInt(cell.innerText));for (let i = 0; i < arr.length - 1; i++) {if (arr[i] === arr[i + 1]) {arr[i] *= 2;score += arr[i];  // 更新分数arr.splice(i + 1, 1);}}while (arr.length < size) arr.push('');return arr.map(num => {let cell = document.createElement('div');cell.classList.add('cell');cell.innerText = num;return cell;});}function handleKey(e) {switch (e.key) {case 'ArrowUp':move('up');break;case 'ArrowDown':move('down');break;case 'ArrowLeft':move('left');break;case 'ArrowRight':move('right');break;}}function updateScore() {scoreElement.innerText = score;}function checkGameOver() {for (let i = 0; i < size; i++) {for (let j = 0; j < size; j++) {let index = i * size + j;if (cells[index].innerText === '') return false;if (j < size - 1 && cells[index].innerText === cells[index + 1].innerText) return false;if (i < size - 1 && cells[index].innerText === cells[index + size].innerText) return false;}}return true;}createBoard();document.addEventListener('keydown', handleKey);
});

这篇关于HTML+CSS+JS实现2048经典小游戏(附完整源码)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1033824

相关文章

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

CSS place-items: center解析与用法详解

《CSSplace-items:center解析与用法详解》place-items:center;是一个强大的CSS简写属性,用于同时控制网格(Grid)和弹性盒(Flexbox)... place-items: center; 是一个强大的 css 简写属性,用于同时控制 网格(Grid) 和 弹性盒(F

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

CSS Anchor Positioning重新定义锚点定位的时代来临(最新推荐)

《CSSAnchorPositioning重新定义锚点定位的时代来临(最新推荐)》CSSAnchorPositioning是一项仍在草案中的新特性,由Chrome125开始提供原生支持需... 目录 css Anchor Positioning:重新定义「锚定定位」的时代来了! 什么是 Anchor Pos

CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比

《CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比》CSS中的position属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布... css 中的 position 属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布局和层叠关

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg