汉诺塔小游戏
<!DOCTYPE html>
<html>
<head>
<title>汉诺塔游戏</title>
<style>
.tower {
position: relative;
display: inline-block;
width: 200px;
height: 300px;
border: 1px solid #000;
margin: 20px;
}
.disk {
position: absolute;
width: 100%;
height: 20px;
background-color: #00f;
transition: left 0.5s, bottom 0.5s;
}
</style>
</head>
<body>
<div class="tower" id="tower1"></div>
<div class="tower" id="tower2"></div>
<div class="tower" id="tower3"></div>
<script src="../js/jquery-3.7.0.min.js"></script>
<script>
$(document).ready(function() {
var numDisks = 3;
var diskHeight = 20;
var towerHeight = 300;
var towerWidth = 200;
var towerPadding = 20;
var selectedDisk = null;
$('.tower').on('click', function() {
var currentTower = $(this);
if (selectedDisk === null) {
var topDisk = currentTower.children('.disk').first();
if (topDisk.length === 0) {
return;
}
selectedDisk = topDisk.detach();
selectedDisk.addClass('selected');
} else {
var targetTower = currentTower;
var targetDisk = currentTower.children('.disk').first();
if (targetDisk.length === 0 || targetDisk.width() > selectedDisk.width()) {
selectedDisk.prependTo(targetTower);
selectedDisk.removeClass('selected');
selectedDisk = null;
} else {
return;
}
}
$('.tower').each(function() {
var tower = $(this);
var disks = tower.children('.disk');
var numDisks = disks.length;
disks.each(function(index) {
var disk = $(this);
var bottom = (numDisks - 1 - index) * diskHeight;
disk.css('bottom', bottom + 'px');
});
});
if ($('#tower3 .disk').length === numDisks) {
console.log('游戏完成!');
setTimeout(() => {
alert("游戏完成!")
}, 500);
}
});
function init() {
var tower1 = $('#tower1');
var towerWidthOffset = (towerWidth - towerPadding) / 2;
for (var i = numDisks; i > 0; i--) {
var diskWidth = i * 40;
var diskLeft = (towerWidth - diskWidth) / 2;
var disk = $('<div class="disk"></div>').css({
width: diskWidth + 'px',
left: diskLeft + 'px'
});
tower1.prepend(disk);
}
$('.tower').each(function() {
var tower = $(this);
var disks = tower.children('.disk');
var numDisks = disks.length;
disks.each(function(index) {
var disk = $(this);
var bottom = (numDisks - 1 - index) * diskHeight;
disk.css('bottom', bottom + 'px');
});
});
}
init();
});
</script>
</body>
</html>