js实现宠物
使用JavaScript实现宠物交互功能
创建一个简单的宠物交互页面需要HTML、CSS和JavaScript的结合。以下是一个基础的实现方式,展示如何在网页上添加一个可交互的宠物元素。
HTML结构
<div id="pet-container">
<div id="pet"></div>
</div>
<button id="feed-btn">喂食</button>
<button id="play-btn">玩耍</button>
CSS样式
#pet-container {
width: 200px;
height: 200px;
position: relative;
}
#pet {
width: 100px;
height: 100px;
background-color: #ffcc00;
border-radius: 50%;
position: absolute;
transition: all 0.3s ease;
}
JavaScript逻辑
const pet = document.getElementById('pet');
const feedBtn = document.getElementById('feed-btn');
const playBtn = document.getElementById('play-btn');
let happiness = 50;
let hunger = 50;
function updatePet() {
pet.style.transform = `scale(${1 + happiness * 0.01})`;
pet.style.backgroundColor = hunger > 70 ? '#ff6666' : '#ffcc00';
}
feedBtn.addEventListener('click', () => {
hunger = Math.max(0, hunger - 20);
happiness = Math.min(100, happiness + 10);
updatePet();
});
playBtn.addEventListener('click', () => {
happiness = Math.min(100, happiness + 20);
hunger = Math.min(100, hunger + 10);
updatePet();
});
// 定期更新状态
setInterval(() => {
happiness = Math.max(0, happiness - 1);
hunger = Math.min(100, hunger + 1);
updatePet();
}, 5000);
实现更复杂的宠物行为
要创建更真实的宠物行为,可以添加以下功能:
随机移动
function moveRandomly() {
const container = document.getElementById('pet-container');
const maxX = container.clientWidth - pet.clientWidth;
const maxY = container.clientHeight - pet.clientHeight;
const newX = Math.floor(Math.random() * maxX);
const newY = Math.floor(Math.random() * maxY);
pet.style.left = `${newX}px`;
pet.style.top = `${newY}px`;
}
setInterval(moveRandomly, 3000);
状态显示
function showStatus() {
console.log(`快乐度: ${happiness}, 饥饿度: ${hunger}`);
if(hunger > 80) {
alert('宠物很饿!');
}
}
使用Canvas创建动画宠物
对于更高级的实现,可以使用Canvas绘制动画宠物:

const canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 400;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
let x = 200, y = 200;
function drawPet() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制身体
ctx.beginPath();
ctx.arc(x, y, 50, 0, Math.PI * 2);
ctx.fillStyle = '#ffcc00';
ctx.fill();
// 绘制眼睛
ctx.beginPath();
ctx.arc(x-20, y-15, 10, 0, Math.PI * 2);
ctx.arc(x+20, y-15, 10, 0, Math.PI * 2);
ctx.fillStyle = '#000';
ctx.fill();
// 根据心情绘制嘴巴
ctx.beginPath();
if(happiness > 70) {
ctx.arc(x, y+10, 20, 0, Math.PI);
} else {
ctx.arc(x, y+20, 20, Math.PI, 0);
}
ctx.stroke();
}
function animate() {
x += (Math.random() - 0.5) * 5;
y += (Math.random() - 0.5) * 5;
// 边界检查
x = Math.max(50, Math.min(canvas.width-50, x));
y = Math.max(50, Math.min(canvas.height-50, y));
drawPet();
requestAnimationFrame(animate);
}
animate();
这些代码示例展示了如何用JavaScript创建基础的宠物交互系统。可以根据需要扩展更多功能,如添加更多状态参数、实现更复杂的动画或增加用户互动方式。






