以下是一个现代风格的QQ农场风格HTML游戏,包含华丽的UI、流畅的动画和丰富的特效。这个游戏使用了HTML5、CSS3和JavaScript,具有响应式设计,适合现代浏览器。
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>星辰农场 - 现代版QQ农场</title>
<style>
:root {
--primary-color: #6a11cb;
--secondary-color: #2575fc;
--accent-color: #ff006e;
--light-color: #f8f9fa;
--dark-color: #212529;
--success-color: #28a745;
--warning-color: #ffc107;
--danger-color: #dc3545;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Microsoft YaHei', 'PingFang SC', 'Arial', sans-serif;
}
body {
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
color: var(--dark-color);
overflow: hidden;
height: 100vh;
display: flex;
flex-direction: column;
}
/* 背景动画 */
.background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
overflow: hidden;
}
.floating-element {
position: absolute;
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
animation: float 15s infinite linear;
}
@keyframes float {
0% {
transform: translateY(0) rotate(0deg);
}
100% {
transform: translateY(-1000px) rotate(720deg);
}
}
/* 头部 */
header {
background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
color: white;
padding: 1rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
position: relative;
overflow: hidden;
}
.header-title {
font-size: 1.8rem;
font-weight: bold;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
display: flex;
align-items: center;
gap: 10px;
}
.header-title i {
font-size: 2rem;
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
.user-info {
display: flex;
align-items: center;
gap: 15px;
background: rgba(255, 255, 255, 0.1);
padding: 8px 15px;
border-radius: 20px;
backdrop-filter: blur(5px);
}
.avatar {
width: 40px;
height: 40px;
border-radius: 50%;
object-fit: cover;
border: 2px solid white;
box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
}
.user-stats {
display: flex;
gap: 10px;
}
.stat-item {
display: flex;
flex-direction: column;
align-items: center;
font-size: 0.8rem;
}
.stat-value {
font-weight: bold;
font-size: 1rem;
color: var(--accent-color);
text-shadow: 0 0 5px rgba(255, 255, 255, 0.5);
}
/* 主内容区 */
.main-content {
flex: 1;
display: flex;
padding: 1rem;
gap: 1rem;
overflow: hidden;
}
/* 左侧面板 */
.left-panel {
width: 250px;
background: white;
border-radius: 15px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
padding: 1rem;
display: flex;
flex-direction: column;
gap: 1rem;
overflow-y: auto;
max-height: calc(100vh - 120px);
}
.panel-title {
font-size: 1.2rem;
font-weight: bold;
margin-bottom: 0.5rem;
color: var(--primary-color);
border-bottom: 2px solid var(--primary-color);
padding-bottom: 0.5rem;
}
.inventory-item {
display: flex;
align-items: center;
gap: 10px;
padding: 8px;
border-radius: 8px;
background: rgba(106, 17, 203, 0.1);
margin-bottom: 5px;
cursor: pointer;
transition: all 0.3s ease;
}
.inventory-item:hover {
background: rgba(106, 17, 203, 0.2);
transform: translateX(5px);
}
.item-icon {
width: 30px;
height: 30px;
object-fit: contain;
}
.item-name {
flex: 1;
font-size: 0.9rem;
}
.item-count {
background: var(--primary-color);
color: white;
width: 20px;
height: 20px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.7rem;
}
/* 中间农场区域 */
.farm-area {
flex: 1;
background: linear-gradient(135deg, #e0f7fa 0%, #b2ebf2 100%);
border-radius: 15px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
position: relative;
overflow: hidden;
}
.farm-grid {
display: grid;
grid-template-columns: repeat(8, 1fr);
gap: 5px;
padding: 10px;
height: calc(100% - 50px);
overflow-y: auto;
}
.plot {
aspect-ratio: 1;
background: rgba(139, 69, 19, 0.3);
border-radius: 8px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: relative;
cursor: pointer;
transition: all 0.3s ease;
border: 2px solid transparent;
}
.plot:hover {
transform: scale(1.05);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
.plot.empty {
background: rgba(139, 69, 19, 0.1);
}
.plot.planted {
background: rgba(34, 139, 34, 0.3);
}
.plot.ready {
background: rgba(255, 215, 0, 0.3);
border-color: var(--success-color);
animation: pulse-glow 2s infinite;
}
@keyframes pulse-glow {
0% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.4); }
70% { box-shadow: 0 0 0 10px rgba(40, 167, 69, 0); }
100% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0); }
}
.plot.withered {
background: rgba(165, 42, 42, 0.3);
border-color: var(--danger-color);
}
.plant {
width: 60%;
height: 60%;
object-fit: contain;
transition: transform 0.5s ease;
position: relative;
z-index: 1;
}
.plant.growing {
animation: grow 3s linear infinite;
}
@keyframes grow {
0% { transform: scale(0.8); }
50% { transform: scale(1.1); }
100% { transform: scale(0.8); }
}
.plot-info {
position: absolute;
bottom: 5px;
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 2px 5px;
border-radius: 10px;
font-size: 0.6rem;
display: flex;
align-items: center;
gap: 3px;
}
.plot-info i {
font-size: 0.7rem;
}
/* 右侧面板 */
.right-panel {
width: 300px;
background: white;
border-radius: 15px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
padding: 1rem;
display: flex;
flex-direction: column;
gap: 1rem;
overflow-y: auto;
max-height: calc(100vh - 120px);
}
.shop-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
border-radius: 8px;
background: rgba(37, 117, 252, 0.1);
margin-bottom: 5px;
cursor: pointer;
transition: all 0.3s ease;
}
.shop-item:hover {
background: rgba(37, 117, 252, 0.2);
transform: translateX(5px);
}
.shop-item .item-icon {
width: 40px;
height: 40px;
}
.shop-item-info {
flex: 1;
}
.shop-item-name {
font-weight: bold;
margin-bottom: 3px;
}
.shop-item-price {
color: var(--accent-color);
font-weight: bold;
}
.shop-item-time {
font-size: 0.8rem;
color: #6c757d;
}
.buy-btn {
background: var(--primary-color);
color: white;
border: none;
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s ease;
}
.buy-btn:hover {
background: var(--secondary-color);
transform: scale(1.05);
}
/* 底部状态栏 */
footer {
background: white;
padding: 0.5rem 1rem;
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.game-stats {
display: flex;
gap: 15px;
}
.stat-box {
background: rgba(106, 17, 203, 0.1);
padding: 5px 10px;
border-radius: 5px;
display: flex;
align-items: center;
gap: 5px;
}
.stat-box i {
color: var(--primary-color);
}
.action-buttons {
display: flex;
gap: 10px;
}
.action-btn {
background: var(--primary-color);
color: white;
border: none;
padding: 8px 15px;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
gap: 5px;
}
.action-btn:hover {
background: var(--secondary-color);
transform: translateY(-2px);
}
.action-btn i {
font-size: 1rem;
}
/* 模态框 */
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 100;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s ease;
}
.modal.active {
opacity: 1;
pointer-events: all;
}
.modal-content {
background: white;
padding: 2rem;
border-radius: 15px;
width: 80%;
max-width: 500px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
transform: translateY(20px);
transition: transform 0.3s ease;
}
.modal.active .modal-content {
transform: translateY(0);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid #eee;
}
.modal-title {
font-size: 1.5rem;
color: var(--primary-color);
}
.close-btn {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #6c757d;
}
.modal-body {
margin-bottom: 1.5rem;
}
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 10px;
}
.btn {
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s ease;
}
.btn-primary {
background: var(--primary-color);
color: white;
border: none;
}
.btn-primary:hover {
background: var(--secondary-color);
}
.btn-secondary {
background: #f8f9fa;
color: var(--dark-color);
border: 1px solid #dee2e6;
}
.btn-secondary:hover {
background: #e9ecef;
}
/* 动画效果 */
.harvest-animation {
position: fixed;
pointer-events: none;
z-index: 1000;
}
.coin {
position: absolute;
width: 20px;
height: 20px;
background: gold;
border-radius: 50%;
animation: coin-fly 1s linear forwards;
}
@keyframes coin-fly {
0% {
transform: translateY(0) scale(1);
opacity: 1;
}
100% {
transform: translateY(-200px) scale(0.5);
opacity: 0;
}
}
/* 响应式设计 */
@media (max-width: 1200px) {
.left-panel, .right-panel {
width: 200px;
}
}
@media (max-width: 992px) {
.main-content {
flex-direction: column;
}
.left-panel, .right-panel {
width: 100%;
max-height: 200px;
}
.farm-area {
height: 400px;
}
}
@media (max-width: 768px) {
.farm-grid {
grid-template-columns: repeat(6, 1fr);
}
.user-info {
flex-direction: column;
gap: 5px;
}
.user-stats {
flex-direction: column;
}
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
<div class="background" id="background"></div>
<header>
<div class="header-title">
<i class="fas fa-seedling"></i>
<span>星辰农场</span>
</div>
<div class="user-info">
<img src="https://randomuser.me/api/portraits/women/44.jpg" alt="用户头像" class="avatar">
<div>
<div class="user-name">玩家昵称</div>
<div class="user-level">Lv. 15</div>
</div>
<div class="user-stats">
<div class="stat-item">
<div class="stat-value">1250</div>
<div>金币</div>
</div>
<div class="stat-item">
<div class="stat-value">48</div>
<div>经验</div>
</div>
</div>
</div>
</header>
<div class="main-content">
<div class="left-panel">
<div class="panel-title">我的背包</div>
<div class="inventory" id="inventory">
<!-- 背包物品将通过JavaScript动态生成 -->
</div>
</div>
<div class="farm-area">
<div class="farm-grid" id="farmGrid">
<!-- 农场土地将通过JavaScript动态生成 -->
</div>
</div>
<div class="right-panel">
<div class="panel-title">商店</div>
<div class="shop" id="shop">
<!-- 商店物品将通过JavaScript动态生成 -->
</div>
</div>
</div>
<footer>
<div class="game-stats">
<div class="stat-box">
<i class="fas fa-clock"></i>
<span id="gameTime">00:00:00</span>
</div>
<div class="stat-box">
<i class="fas fa-leaf"></i>
<span id="totalPlants">0</span> 株作物
</div>
<div class="stat-box">
<i class="fas fa-coins"></i>
<span id="totalCoins">0</span> 金币
</div>
</div>
<div class="action-buttons">
<button class="action-btn" id="harvestAllBtn">
<i class="fas fa-scissors"></i> 一键收割
</button>
<button class="action-btn" id="waterAllBtn">
<i class="fas fa-tint"></i> 一键浇水
</button>
</div>
</footer>
<!-- 模态框 -->
<div class="modal" id="modal">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title" id="modalTitle">标题</h2>
<button class="close-btn" id="closeModal">×</button>
</div>
<div class="modal-body" id="modalBody">
内容
</div>
<div class="modal-footer">
<button class="btn btn-secondary" id="cancelBtn">取消</button>
<button class="btn btn-primary" id="confirmBtn">确认</button>
</div>
</div>
</div>
<div class="harvest-animation" id="harvestAnimation"></div>
<script>
// 游戏数据
const gameData = {
user: {
name: "玩家昵称",
level: 15,
coins: 1250,
exp: 48,
avatar: "https://randomuser.me/api/portraits/women/44.jpg"
},
inventory: [
{ id: 1, name: "小麦种子", type: "seed", count: 10, icon: "https://cdn-icons-png.flaticon.com/512/3174/3174745.png" },
{ id: 2, name: "胡萝卜种子", type: "seed", count: 5, icon: "https://cdn-icons-png.flaticon.com/512/3174/3174747.png" },
{ id: 3, name: "水", type: "tool", count: 20, icon: "https://cdn-icons-png.flaticon.com/512/3174/3174749.png" },
{ id: 4, name: "肥料", type: "tool", count: 3, icon: "https://cdn-icons-png.flaticon.com/512/3174/3174751.png" }
],
shopItems: [
{ id: 1, name: "小麦种子", type: "seed", price: 10, time: 30, icon: "https://cdn-icons-png.flaticon.com/512/3174/3174745.png" },
{ id: 2, name: "胡萝卜种子", type: "seed", price: 20, time: 60, icon: "https://cdn-icons-png.flaticon.com/512/3174/3174747.png" },
{ id: 3, name: "西红柿种子", type: "seed", price: 30, time: 90, icon: "https://cdn-icons-png.flaticon.com/512/3174/3174748.png" },
{ id: 4, name: "水", type: "tool", price: 5, time: 0, icon: "https://cdn-icons-png.flaticon.com/512/3174/3174749.png" },
{ id: 5, name: "肥料", type: "tool", price: 15, time: 0, icon: "https://cdn-icons-png.flaticon.com/512/3174/3174751.png" }
],
farm: Array(48).fill().map((_, index) => ({
id: index + 1,
status: "empty",
plantId: null,
plantTime: null,
growth: 0,
watered: false,
fertilized: false
})),
plants: {
1: { name: "小麦", icon: "https://cdn-icons-png.flaticon.com/512/3174/3174745.png", harvestValue: 15 },
2: { name: "胡萝卜", icon: "https://cdn-icons-png.flaticon.com/512/3174/3174747.png", harvestValue: 25 },
3: { name: "西红柿", icon: "https://cdn-icons-png.flaticon.com/512/3174/3174748.png", harvestValue: 35 }
},
gameTime: 0,
gameSpeed: 1,
selectedItem: null
};
// DOM元素
const elements = {
inventory: document.getElementById('inventory'),
shop: document.getElementById('shop'),
farmGrid: document.getElementById('farmGrid'),
gameTime: document.getElementById('gameTime'),
totalPlants: document.getElementById('totalPlants'),
totalCoins: document.getElementById('totalCoins'),
modal: document.getElementById('modal'),
modalTitle: document.getElementById('modalTitle'),
modalBody: document.getElementById('modalBody'),
confirmBtn: document.getElementById('confirmBtn'),
cancelBtn: document.getElementById('cancelBtn'),
closeModal: document.getElementById('closeModal'),
harvestAllBtn: document.getElementById('harvestAllBtn'),
waterAllBtn: document.getElementById('waterAllBtn'),
harvestAnimation: document.getElementById('harvestAnimation'),
background: document.getElementById('background')
};
// 初始化游戏
function initGame() {
renderInventory();
renderShop();
renderFarm();
updateGameStats();
createBackgroundElements();
setupEventListeners();
startGameLoop();
}
// 渲染背包
function renderInventory() {
elements.inventory.innerHTML = '';
gameData.inventory.forEach(item => {
const itemElement = document.createElement('div');
itemElement.className = 'inventory-item';
itemElement.dataset.id = item.id;
itemElement.dataset.type = item.type;
itemElement.innerHTML = `
<img src="${item.icon}" alt="${item.name}" class="item-icon">
<div class="item-name">${item.name}</div>
<div class="item-count">${item.count}</div>
`;
itemElement.addEventListener('click', () => {
selectItem(item);
});
elements.inventory.appendChild(itemElement);
});
}
// 渲染商店
function renderShop() {
elements.shop.innerHTML = '';
gameData.shopItems.forEach(item => {
const itemElement = document.createElement('div');
itemElement.className = 'shop-item';
itemElement.dataset.id = item.id;
itemElement.innerHTML = `
<img src="${item.icon}" alt="${item.name}" class="item-icon">
<div class="shop-item-info">
<div class="shop-item-name">${item.name}</div>
<div class="shop-item-price">${item.price} 金币</div>
${item.time > 0 ? `<div class="shop-item-time">成长时间: ${item.time}秒</div>` : ''}
</div>
<button class="buy-btn">购买</button>
`;
itemElement.querySelector('.buy-btn').addEventListener('click', (e) => {
e.stopPropagation();
buyItem(item);
});
elements.shop.appendChild(itemElement);
});
}
// 渲染农场
function renderFarm() {
elements.farmGrid.innerHTML = '';
gameData.farm.forEach(plot => {
const plotElement = document.createElement('div');
plotElement.className = `plot ${plot.status}`;
plotElement.dataset.id = plot.id;
if (plot.status === 'planted') {
const plant = gameData.plants[plot.plantId];
const growthPercentage = Math.min(100, plot.growth);
const isReady = growthPercentage >= 100;
plotElement.innerHTML = `
<img src="${plant.icon}" alt="${plant.name}" class="plant ${isReady ? '' : 'growing'}">
<div class="plot-info">
<i class="fas fa-hourglass-half"></i>
<span>${growthPercentage}%</span>
</div>
`;
if (isReady) {
plotElement.classList.add('ready');
}
} else if (plot.status === 'withered') {
plotElement.innerHTML = `
<i class="fas fa-skull-crossbones" style="font-size: 2rem; color: var(--danger-color);"></i>
`;
}
plotElement.addEventListener('click', () => {
handlePlotClick(plot);
});
elements.farmGrid.appendChild(plotElement);
});
}
// 更新游戏状态
function updateGameStats() {
// 更新游戏时间
const hours = Math.floor(gameData.gameTime / 3600);
const minutes = Math.floor((gameData.gameTime % 3600) / 60);
const seconds = gameData.gameTime % 60;
elements.gameTime.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
// 更新作物总数
const plantedPlots = gameData.farm.filter(plot => plot.status === 'planted').length;
elements.totalPlants.textContent = plantedPlots;
// 更新金币数量
elements.totalCoins.textContent = gameData.user.coins;
}
// 创建背景动画元素
function createBackgroundElements() {
const colors = ['rgba(255, 255, 255, 0.2)', 'rgba(106, 17, 203, 0.2)', 'rgba(37, 117, 252, 0.2)'];
for (let i = 0; i < 15; i++) {
const element = document.createElement('div');
element.className = 'floating-element';
element.style.width = `${Math.random() * 50 + 20}px`;
element.style.height = element.style.width;
element.style.left = `${Math.random() * 100}%`;
element.style.top = `${Math.random() * 100 + 100}%`;
element.style.background = colors[Math.floor(Math.random() * colors.length)];
element.style.animationDuration = `${Math.random() * 20 + 10}s`;
element.style.animationDelay = `${Math.random() * 5}s`;
elements.background.appendChild(element);
}
}
// 设置事件监听器
function setupEventListeners() {
// 模态框按钮
elements.confirmBtn.addEventListener('click', () => {
elements.modal.classList.remove('active');
});
elements.cancelBtn.addEventListener('click', () => {
elements.modal.classList.remove('active');
});
elements.closeModal.addEventListener('click', () => {
elements.modal.classList.remove('active');
});
// 一键收割
elements.harvestAllBtn.addEventListener('click', () => {
harvestAllPlots();
});
// 一键浇水
elements.waterAllBtn.addEventListener('click', () => {
waterAllPlots();
});
// 防止模态框事件冒泡
elements.modal.addEventListener('click', (e) => {
if (e.target === elements.modal) {
elements.modal.classList.remove('active');
}
});
}
// 选择物品
function selectItem(item) {
gameData.selectedItem = item;
const inventoryItems = document.querySelectorAll('.inventory-item');
inventoryItems.forEach(itemElement => {
itemElement.style.border = 'none';
});
const selectedElement = document.querySelector(`.inventory-item[data-id="${item.id}"]`);
if (selectedElement) {
selectedElement.style.border = '2px solid var(--primary-color)';
}
}
// 处理土地点击
function handlePlotClick(plot) {
if (!gameData.selectedItem) {
showModal('提示', '请先选择一个物品');
return;
}
if (plot.status === 'empty' && gameData.selectedItem.type === 'seed') {
plantSeed(plot.id, gameData.selectedItem.id);
} else if (plot.status === 'planted' && gameData.selectedItem.type === 'tool') {
if (gameData.selectedItem.id === 3) { // 水
waterPlot(plot.id);
} else if (gameData.selectedItem.id === 5) { // 肥料
fertilizePlot(plot.id);
}
} else if (plot.status === 'ready') {
harvestPlot(plot.id);
} else if (plot.status === 'withered') {
clearPlot(plot.id);
} else {
showModal('提示', '无法在此土地上执行此操作');
}
}
// 种植种子
function plantSeed(plotId, seedId) {
const plotIndex = gameData.farm.findIndex(plot => plot.id === plotId);
if (plotIndex === -1) return;
const seedItem = gameData.inventory.find(item => item.id === seedId);
if (!seedItem || seedItem.count <= 0) {
showModal('提示', '没有足够的种子');
return;
}
const plot = gameData.farm[plotIndex];
if (plot.status !== 'empty') {
showModal('提示', '这块土地已经有作物了');
return;
}
// 扣除种子
seedItem.count--;
if (seedItem.count === 0) {
gameData.inventory = gameData.inventory.filter(item => item.id !== seedId);
gameData.selectedItem = null;
renderInventory();
} else {
renderInventory();
}
// 种植作物
plot.status = 'planted';
plot.plantId = seedId;
plot.plantTime = gameData.gameTime;
plot.growth = 0;
plot.watered = false;
plot.fertilized = false;
renderFarm();
}
// 浇水
function waterPlot(plotId) {
const plotIndex = gameData.farm.findIndex(plot => plot.id === plotId);
if (plotIndex === -1) return;
const waterItem = gameData.inventory.find(item => item.id === 3);
if (!waterItem || waterItem.count <= 0) {
showModal('提示', '没有足够的水');
return;
}
const plot = gameData.farm[plotIndex];
if (plot.status !== 'planted') {
showModal('提示', '这块土地没有作物');
return;
}
if (plot.watered) {
showModal('提示', '这块土地已经浇过水了');
return;
}
// 扣除水
waterItem.count--;
if (waterItem.count === 0) {
gameData.inventory = gameData.inventory.filter(item => item.id === 3);
gameData.selectedItem = null;
renderInventory();
} else {
renderInventory();
}
// 浇水
plot.watered = true;
showModal('成功', '土地已经浇水,作物生长速度提高20%');
}
// 施肥
function fertilizePlot(plotId) {
const plotIndex = gameData.farm.findIndex(plot => plot.id === plotId);
if (plotIndex === -1) return;
const fertilizerItem = gameData.inventory.find(item => item.id === 5);
if (!fertilizerItem || fertilizerItem.count <= 0) {
showModal('提示', '没有足够的肥料');
return;
}
const plot = gameData.farm[plotIndex];
if (plot.status !== 'planted') {
showModal('提示', '这块土地没有作物');
return;
}
if (plot.fertilized) {
showModal('提示', '这块土地已经施过肥了');
return;
}
// 扣除肥料
fertilizerItem.count--;
if (fertilizerItem.count === 0) {
gameData.inventory = gameData.inventory.filter(item => item.id === 5);
gameData.selectedItem = null;
renderInventory();
} else {
renderInventory();
}
// 施肥
plot.fertilized = true;
showModal('成功', '土地已经施肥,作物生长速度提高50%');
}
// 收割作物
function harvestPlot(plotId) {
const plotIndex = gameData.farm.findIndex(plot => plot.id === plotId);
if (plotIndex === -1) return;
const plot = gameData.farm[plotIndex];
if (plot.status !== 'ready') {
showModal('提示', '作物还没有成熟');
return;
}
const plant = gameData.plants[plot.plantId];
if (!plant) return;
// 获得金币
gameData.user.coins += plant.harvestValue;
updateGameStats();
// 播放收割动画
playHarvestAnimation(plotId, plant.harvestValue);
// 清空土地
plot.status = 'empty';
plot.plantId = null;
plot.plantTime = null;
plot.growth = 0;
plot.watered = false;
plot.fertilized = false;
renderFarm();
}
// 一键收割
function harvestAllPlots() {
let totalHarvest = 0;
gameData.farm.forEach(plot => {
if (plot.status === 'ready') {
const plant = gameData.plants[plot.plantId];
if (plant) {
totalHarvest += plant.harvestValue;
}
}
});
if (totalHarvest === 0) {
showModal('提示', '没有可以收割的作物');
return;
}
gameData.farm.forEach(plot => {
if (plot.status === 'ready') {
const plant = gameData.plants[plot.plantId];
if (plant) {
// 播放收割动画
playHarvestAnimation(plot.id, plant.harvestValue);
// 清空土地
plot.status = 'empty';
plot.plantId = null;
plot.plantTime = null;
plot.growth = 0;
plot.watered = false;
plot.fertilized = false;
}
}
});
// 获得金币
gameData.user.coins += totalHarvest;
updateGameStats();
renderFarm();
showModal('成功', `成功收割所有作物,获得${totalHarvest}金币`);
}
// 一键浇水
function waterAllPlots() {
const waterItem = gameData.inventory.find(item => item.id === 3);
if (!waterItem || waterItem.count <= 0) {
showModal('提示', '没有足够的水');
return;
}
let wateredCount = 0;
gameData.farm.forEach(plot => {
if (plot.status === 'planted' && !plot.watered) {
plot.watered = true;
wateredCount++;
}
});
if (wateredCount === 0) {
showModal('提示', '没有需要浇水的土地');
return;
}
// 扣除水
waterItem.count -= wateredCount;
if (waterItem.count <= 0) {
gameData.inventory = gameData.inventory.filter(item => item.id !== 3);
gameData.selectedItem = null;
}
renderInventory();
renderFarm();
showModal('成功', `成功浇水${wateredCount}块土地`);
}
// 清理土地
function clearPlot(plotId) {
const plotIndex = gameData.farm.findIndex(plot => plot.id === plotId);
if (plotIndex === -1) return;
const plot = gameData.farm[plotIndex];
plot.status = 'empty';
plot.plantId = null;
plot.plantTime = null;
plot.growth = 0;
plot.watered = false;
plot.fertilized = false;
renderFarm();
}
// 购买物品
function buyItem(item) {
if (gameData.user.coins < item.price) {
showModal('提示', '金币不足');
return;
}
// 扣除金币
gameData.user.coins -= item.price;
updateGameStats();
// 添加到背包
const existingItem = gameData.inventory.find(invItem => invItem.id === item.id);
if (existingItem) {
existingItem.count += 1;
} else {
gameData.inventory.push({
id: item.id,
name: item.name,
type: item.type,
count: 1,
icon: item.icon
});
}
renderInventory();
showModal('成功', `成功购买${item.name}`);
}
// 显示模态框
function showModal(title, message) {
elements.modalTitle.textContent = title;
elements.modalBody.textContent = message;
elements.modal.classList.add('active');
}
// 播放收割动画
function playHarvestAnimation(plotId, coins) {
const plotElement = document.querySelector(`.plot[data-id="${plotId}"]`);
if (!plotElement) return;
const rect = plotElement.getBoundingClientRect();
const startX = rect.left + rect.width / 2;
const startY = rect.top + rect.height / 2;
// 创建金币动画
for (let i = 0; i < coins; i++) {
setTimeout(() => {
const coin = document.createElement('div');
coin.className = 'coin';
coin.style.left = `${startX}px`;
coin.style.top = `${startY}px`;
coin.style.animationDelay = `${i * 0.1}s`;
elements.harvestAnimation.appendChild(coin);
// 动画结束后移除金币
setTimeout(() => {
coin.remove();
}, 1000);
}, i * 50);
}
}
// 游戏循环
function startGameLoop() {
setInterval(() => {
gameData.gameTime += 1 * gameData.gameSpeed;
updateGameStats();
updatePlantGrowth();
}, 1000);
}
// 更新作物生长
function updatePlantGrowth() {
let needsUpdate = false;
gameData.farm.forEach(plot => {
if (plot.status === 'planted') {
const plant = gameData.plants[plot.plantId];
if (!plant) return;
const timePassed = gameData.gameTime - plot.plantTime;
const baseGrowthTime = plant.time; // 基础生长时间
// 计算生长速度修正
let growthModifier = 1;
if (plot.watered) growthModifier += 0.2;
if (plot.fertilized) growthModifier += 0.5;
const effectiveGrowthTime = baseGrowthTime / growthModifier;
const growthPercentage = Math.min(100, (timePassed / effectiveGrowthTime) * 100);
if (growthPercentage !== plot.growth) {
plot.growth = growthPercentage;
needsUpdate = true;
}
// 检查是否枯萎
if (timePassed > baseGrowthTime * 1.5 && !plot.watered) {
plot.status = 'withered';
needsUpdate = true;
}
}
});
if (needsUpdate) {
renderFarm();
}
}
// 初始化游戏
initGame();
</script>
</body>
</html>
这个游戏完全使用HTML、CSS和JavaScript实现,无需任何外部依赖,可以直接在浏览器中运行。您可以将此代码保存为HTML文件,然后在浏览器中打开即可玩游戏。