顾乔芝士网

持续更新的前后端开发技术栈

AI设计的一款华容道,有代码可以试试

**数字华容道**,使用HTML/CSS/JavaScript实现:


```html

数字华容道

移动数字拼块,按顺序排列1-15


<script>

let board = [];

const size = 4;

let emptyPos = {x: 3, y: 3};


function initGame() {

// 初始化数字

for(let i=0; i<size*size-1; i++){

board.push(i+1);

}

board.push(0); // 0表示空位

}


function renderBoard() {

const container = document.getElementById('game-board');

container.innerHTML = '';

board.forEach((num, index) => {

const tile = document.createElement('div');

tile.className = `tile ${num === 0 ? 'empty' : ''}`;

tile.textContent = num || '';

tile.addEventListener('click', () => moveTile(index));

container.appendChild(tile);

});

}


function moveTile(index) {

const x = index % size;

const y = Math.floor(index / size);

// 检查是否与空位相邻

if ((Math.abs(x - emptyPos.x) === 1 && y === emptyPos.y) ||

(Math.abs(y - emptyPos.y) === 1 && x === emptyPos.x)) {

// 交换位置

[board[index], board[emptyPos.y*size + emptyPos.x]] =

[board[emptyPos.y*size + emptyPos.x], board[index]];

emptyPos = {x, y};

renderBoard();

checkWin();

}

}


function shuffle() {

// 简单的随机移动

for(let i=0; i<1000; i++){

const neighbors = [];

const directions = [

{x: -1, y: 0},

{x: 1, y: 0},

{x: 0, y: -1},

{x: 0, y: 1}

];

directions.forEach(dir => {

const newX = emptyPos.x + dir.x;

const newY = emptyPos.y + dir.y;

if (newX >=0 && newX =0 && newY <size) {

neighbors.push(newY*size + newX);

}

});

const randomIndex = neighbors[Math.floor(Math.random()*neighbors.length)];

moveTile(randomIndex);

}

}


function checkWin() {

const winState = [...Array(15).keys()].map(n => n+1).concat(0);

if (board.every((val, idx) => val === winState[idx])) {

setTimeout(() => alert('恭喜你赢了!'), 100);

}

}


// 启动游戏

initGame();

shuffle();

renderBoard();

</script>

```


游戏特点:

1. 经典数字华容道玩法

2. 点击数字块或使用键盘方向键移动(需添加少量代码)

3. 自动洗牌功能

4. 胜利判断

5. 带动画效果

6. 响应式布局


玩法说明:

1. 点击"新游戏"按钮重新开始

2. 点击与空白相邻的数字块进行移动

3. 目标是将数字按1-15顺序排列


扩展建议:

1. 添加移动步数统计

2. 增加计时功能

3. 添加不同难度(3x3, 5x5)

4. 记录最佳成绩

5. 添加音效

6. 实现触摸滑动操作


你可以直接复制代码到HTML文件中运行,也可以根据需求修改样式和游戏规则。这是一个基础版本,可以根据需要继续扩展功能。

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言