📅  最后修改于: 2023-12-03 15:05:50.479000             🧑  作者: Mango
本篇介绍的是一个用HTML编写的虚拟宠物程序。该程序模拟了用户与虚拟宠物之间的互动,包括喂食、玩耍、清洁等功能。用户可以通过与虚拟宠物的交互,获得愉悦值、能量值等数据反馈,并通过这些数据决定下一步的操作。
该程序实现了以下基本功能:
<!DOCTYPE html>
<html>
<head>
<title>Virtual Pet Comp 105</title>
</head>
<body>
<!--宠物展示区域-->
<div>
<h3>宠物状态</h3>
<ul>
<li>饥饿程度:{{hunger}}</li>
<li>愉悦程度:{{happiness}}</li>
<li>能量值:{{energy}}</li>
<li>清洁度:{{cleanliness}}</li>
</ul>
</div>
<!--食物区域-->
<div>
<h3>喂食</h3>
<select id="foods">
<option value="1">狗粮</option>
<option value="2">鲜肉</option>
<option value="3">鱼肉</option>
</select>
<button onclick="feed()">喂食</button>
</div>
<!--游戏区域-->
<div>
<h3>玩游戏</h3>
<select id="games">
<option value="1">扔球</option>
<option value="2">抓迷藏</option>
<option value="3">追光点</option>
</select>
<button onclick="play()">开始游戏</button>
</div>
<!--清洁区域-->
<div>
<h3>清洁</h3>
<select id="cleanOptions">
<option value="1">洗澡</option>
<option value="2">擦拭</option>
<option value="3">扫地</option>
</select>
<button onclick="clean()">开始清洁</button>
</div>
<!--操作提示-->
<div>
<h3>操作提示</h3>
<p>{{message}}</p>
</div>
<!--Javascript代码-->
<script>
let hunger = 100;
let happiness = 100;
let energy = 100;
let cleanliness = 100;
let message = '';
// 喂食函数
function feed() {
const select = document.getElementById('foods');
const selectedValue = select.options[select.selectedIndex].value;
if (selectedValue == '1') {
hunger += 10;
} else if (selectedValue == '2') {
happiness += 15;
energy -= 10;
cleanliness -= 5;
hunger += 20;
} else if (selectedValue == '3') {
happiness += 10;
energy -= 10;
cleanliness -= 10;
hunger += 20;
}
if (hunger >= 100) {
hunger = 100;
message = '宠物已经吃饱了';
} else {
message = '宠物正在吃东西';
}
}
// 玩游戏函数
function play() {
const select = document.getElementById('games');
const selectedValue = select.options[select.selectedIndex].value;
if (selectedValue == '1') {
happiness += 20;
energy -= 10;
cleanliness -= 5;
} else if (selectedValue == '2') {
happiness += 25;
energy -= 20;
cleanliness -= 10;
} else if (selectedValue == '3') {
happiness += 15;
energy -= 10;
cleanliness -= 5;
}
if (happiness >= 100) {
happiness = 100;
message = '宠物非常愉悦';
} else {
message = '宠物正在玩游戏';
}
}
// 清洁函数
function clean() {
const select = document.getElementById('cleanOptions');
const selectedValue = select.options[select.selectedIndex].value;
if (selectedValue == '1') {
energy -= 10;
happiness += 5;
cleanliness += 20;
} else if (selectedValue == '2') {
energy -= 5;
happiness += 10;
cleanliness += 10;
} else if (selectedValue == '3') {
energy -= 10;
happiness += 5;
cleanliness += 15;
}
if (cleanliness >= 100) {
cleanliness = 100;
message = '宠物已经很干净了';
} else {
message = '宠物正在清洁';
}
}
</script>
</body>
</html>
以上就是一个用HTML编写的虚拟宠物程序。程序实现了基本的喂食、玩游戏、清洁等功能,并且提供了数据反馈和操作提示,使用户能够更好地与虚拟宠物互动。程序代码简洁易懂,可以方便地进行二次开发和修改。