写不动代码了,来个摸鱼小游戏,哈哈哈,纯属记录,自娱自乐。
先新建一个文本,将代码粘贴进去,然后将后缀改为html用浏览器打开就可以啦啦啦啦
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>贪吃蛇小游戏 - 地狱难度版</title>
<style>
:root {
--snake-color: #4CAF50;
--snake-head-color: #388E3C;
--food-color: #F44336;
--obstacle-color: #607D8B;
--bg-color: #f5f5f5;
--board-color: #333;
--text-color: #212121;
--button-color: #2196F3;
--button-hover: #1976D2;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
padding: 20px;
background-color: var(--bg-color);
font-family: 'Arial', sans-serif;
color: var(--text-color);
}
#game-header {
text-align: center;
margin-bottom: 20px;
}
#game-title {
font-size: 2.5rem;
margin: 0;
color: var(--text-color);
text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}
#game-info {
display: flex;
justify-content: space-between;
width: 100%;
max-width: 400px;
margin-bottom: 15px;
}
#score-board {
font-size: 1.5rem;
font-weight: bold;
}
#high-score-board {
font-size: 1.2rem;
color: #757575;
}
#difficulty-select {
font-size: 1rem;
padding: 8px 12px;
border-radius: 4px;
border: 1px solid #BDBDBD;
background-color: white;
margin-bottom: 15px;
}
#game-board {
display: grid;
grid-template-columns: repeat(20, 1fr);
grid-template-rows: repeat(20, 1fr);
gap: 1px;
background-color: var(--board-color);
width: 100%;
max-width: 400px;
max-height: 400px;
aspect-ratio: 1/1;
margin-bottom: 20px;
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}
.cell {
background-color: white;
transition: background-color 0.1s;
}
.snake {
background-color: var(--snake-color);
}
.snake-head {
background-color: var(--snake-head-color);
position: relative;
}
.snake-head::after {
content: '';
position: absolute;
width: 30%;
height: 30%;
background-color: white;
border-radius: 50%;
}
.food {
background-color: var(--food-color);
border-radius: 50%;
animation: pulse 0.5s infinite alternate;
}
.obstacle {
background-color: var(--obstacle-color);
}
#control-buttons {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 5px;
width: 100%;
max-width: 200px;
margin-bottom: 20px;
}
.control-button {
height: 50px;
font-size: 1.5rem;
background-color: var(--button-color);
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.control-button:hover {
background-color: var(--button-hover);
transform: scale(1.05);
}
#empty-top-left, #empty-top-right,
#empty-center, #empty-bottom-left,
#empty-bottom-right {
background-color: transparent;
pointer-events: none;
}
#restart-button {
font-size: 1.2rem;
padding: 12px 24px;
background-color: var(--button-color);
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: all 0.2s;
}
#restart-button:hover {
background-color: var(--button-hover);
transform: scale(1.05);
}
#game-over {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.8);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 100;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s;
}
#game-over.show {
opacity: 1;
pointer-events: all;
}
#game-over-content {
background-color: white;
padding: 30px;
border-radius: 8px;
text-align: center;
max-width: 80%;
}
#game-over h2 {
margin-top: 0;
color: var(--food-color);
}
#final-score {
font-size: 1.5rem;
margin: 20px 0;
}
@keyframes pulse {
from { transform: scale(0.9); }
to { transform: scale(1.1); }
}
@media (max-width: 500px) {
#game-title {
font-size: 2rem;
}
#game-board {
max-width: 300px;
max-height: 300px;
}
.control-button {
height: 40px;
font-size: 1.2rem;
}
}
</style>
</head>
<body>
<div id="game-header">
<h1 id="game-title">贪吃蛇小游戏</h1>
</div>
<div id="game-info">
<div id="score-board">得分: 0</div>
<div id="high-score-board">最高分: 0</div>
</div>
<select id="difficulty-select">
<option value="200">简单</option>
<option value="150">中等</option>
<option value="100">困难</option>
<option value="70">地狱</option>
</select>
<div id="game-board"></div>
<div id="control-buttons">
<button id="empty-top-left"></button>
<button id="up-button" class="control-button">↑</button>
<button id="empty-top-right"></button>
<button id="left-button" class="control-button">←</button>
<button id="empty-center"></button>
<button id="right-button" class="control-button">→</button>
<button id="empty-bottom-left"></button>
<button id="down-button" class="control-button">↓</button>
<button id="empty-bottom-right"></button>
</div>
<button id="restart-button">重新开始</button>
<div id="game-over">
<div id="game-over-content">
<h2>游戏结束!</h2>
<div id="final-score">最终得分: 0</div>
<button id="restart-button-modal" class="control-button">再玩一次</button>
</div>
</div>
<script>
// 游戏配置
const config = {
boardSize: 20,
initialSpeed: 200,
speeds: {
easy: 200,
medium: 150,
hard: 100,
hell: 70
},
scoreIncrement: 10,
hellModeObstacles: 30
};
// 游戏状态
const state = {
snake: [{x: 10, y: 10}],
food: null,
obstacles: [],
direction: 'right',
nextDirection: 'right',
score: 0,
highScore: localStorage.getItem('snakeHighScore') || 0,
gameInterval: null,
isGameOver: false,
difficulty: 'easy'
};
// DOM元素
const elements = {
gameBoard: document.getElementById('game-board'),
scoreBoard: document.getElementById('score-board'),
highScoreBoard: document.getElementById('high-score-board'),
difficultySelect: document.getElementById('difficulty-select'),
restartButton: document.getElementById('restart-button'),
restartButtonModal: document.getElementById('restart-button-modal'),
gameOver: document.getElementById('game-over'),
finalScore: document.getElementById('final-score'),
upButton: document.getElementById('up-button'),
leftButton: document.getElementById('left-button'),
downButton: document.getElementById('down-button'),
rightButton: document.getElementById('right-button')
};
// 初始化游戏
function initGame() {
// 清空游戏板
elements.gameBoard.innerHTML = '';
// 创建游戏板单元格
for (let y = 0; y < config.boardSize; y++) {
for (let x = 0; x < config.boardSize; x++) {
const cell = document.createElement('div');
cell.className = 'cell';
cell.dataset.x = x;
cell.dataset.y = y;
elements.gameBoard.appendChild(cell);
}
}
// 重置游戏状态
state.snake = [{x: 10, y: 10}];
state.direction = 'right';
state.nextDirection = 'right';
state.score = 0;
state.isGameOver = false;
state.obstacles = [];
// 更新分数显示
updateScore();
// 生成食物和障碍物
generateFood();
if (state.difficulty === 'hell') {
generateObstacles();
}
// 绘制游戏
drawGame();
// 隐藏游戏结束界面
elements.gameOver.classList.remove('show');
// 清除之前的游戏循环
if (state.gameInterval) {
clearInterval(state.gameInterval);
}
// 开始游戏循环
startGameLoop();
}
// 开始游戏循环
function startGameLoop() {
const speed = config.speeds[state.difficulty] || config.initialSpeed;
state.gameInterval = setInterval(gameLoop, speed);
}
// 游戏主循环
function gameLoop() {
// 更新方向
state.direction = state.nextDirection;
// 移动蛇
moveSnake();
// 检查碰撞
if (checkCollisions()) {
gameOver();
return;
}
// 检查是否吃到食物
checkFood();
// 绘制游戏
drawGame();
}
// 移动蛇
function moveSnake() {
const head = {...state.snake[0]};
switch (state.direction) {
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
case 'left':
head.x--;
break;
case 'right':
head.x++;
break;
}
// 添加新头部
state.snake.unshift(head);
// 移除尾部(如果没有吃到食物)
if (!(head.x === state.food.x && head.y === state.food.y)) {
state.snake.pop();
}
}
// 检查碰撞
function checkCollisions() {
const head = state.snake[0];
// 检查墙壁碰撞
if (head.x < 0 || head.x >= config.boardSize ||
head.y < 0 || head.y >= config.boardSize) {
return true;
}
// 检查自身碰撞(跳过头部)
for (let i = 1; i < state.snake.length; i++) {
if (head.x === state.snake[i].x && head.y === state.snake[i].y) {
return true;
}
}
// 检查障碍物碰撞(地狱模式)
if (state.difficulty === 'hell') {
for (const obstacle of state.obstacles) {
if (head.x === obstacle.x && head.y === obstacle.y) {
return true;
}
}
}
return false;
}
// 检查食物
function checkFood() {
const head = state.snake[0];
if (head.x === state.food.x && head.y === state.food.y) {
// 增加分数
state.score += config.scoreIncrement;
updateScore();
// 生成新食物
generateFood();
// 地狱模式下增加障碍物
if (state.difficulty === 'hell' && state.score % 50 === 0) {
generateObstacles(2);
}
}
}
// 生成食物
function generateFood() {
let foodPosition;
let isValidPosition = false;
while (!isValidPosition) {
foodPosition = {
x: Math.floor(Math.random() * config.boardSize),
y: Math.floor(Math.random() * config.boardSize)
};
// 检查食物是否在蛇身上
isValidPosition = !state.snake.some(segment =>
segment.x === foodPosition.x && segment.y === foodPosition.y);
// 检查食物是否在障碍物上(地狱模式)
if (isValidPosition && state.difficulty === 'hell') {
isValidPosition = !state.obstacles.some(obstacle =>
obstacle.x === foodPosition.x && obstacle.y === foodPosition.y);
}
}
state.food = foodPosition;
}
// 生成障碍物(地狱模式)
function generateObstacles(count = 1) {
for (let i = 0; i < count; i++) {
let obstaclePosition;
let isValidPosition = false;
while (!isValidPosition) {
obstaclePosition = {
x: Math.floor(Math.random() * config.boardSize),
y: Math.floor(Math.random() * config.boardSize)
};
// 检查障碍物是否在蛇身上
isValidPosition = !state.snake.some(segment =>
segment.x === obstaclePosition.x && segment.y === obstaclePosition.y);
// 检查障碍物是否在食物上
if (isValidPosition) {
isValidPosition = !(obstaclePosition.x === state.food.x &&
obstaclePosition.y === state.food.y);
}
// 检查障碍物是否与其他障碍物重叠
if (isValidPosition) {
isValidPosition = !state.obstacles.some(obstacle =>
obstacle.x === obstaclePosition.x && obstacle.y === obstaclePosition.y);
}
}
state.obstacles.push(obstaclePosition);
// 限制障碍物数量
if (state.obstacles.length > config.hellModeObstacles) {
state.obstacles.shift();
}
}
}
// 绘制游戏
function drawGame() {
// 清除所有单元格的类
const cells = document.querySelectorAll('.cell');
cells.forEach(cell => {
cell.className = 'cell';
});
// 绘制障碍物(地狱模式)
if (state.difficulty === 'hell') {
state.obstacles.forEach(obstacle => {
const cell = document.querySelector(`.cell[data-x="${obstacle.x}"][data-y="${obstacle.y}"]`);
if (cell) cell.classList.add('obstacle');
});
}
// 绘制食物
const foodCell = document.querySelector(`.cell[data-x="${state.food.x}"][data-y="${state.food.y}"]`);
if (foodCell) foodCell.classList.add('food');
// 绘制蛇身
state.snake.forEach((segment, index) => {
const cell = document.querySelector(`.cell[data-x="${segment.x}"][data-y="${segment.y}"]`);
if (cell) {
cell.classList.add(index === 0 ? 'snake-head' : 'snake');
// 添加蛇头眼睛
if (index === 0) {
cell.style.setProperty('--eye1-x', state.direction === 'left' ? '30%' : '70%');
cell.style.setProperty('--eye1-y', state.direction === 'up' ? '30%' : '70%');
cell.style.setProperty('--eye2-x', state.direction === 'left' ? '30%' : '70%');
cell.style.setProperty('--eye2-y', state.direction === 'up' ? '70%' : '30%');
}
}
});
}
// 更新分数
function updateScore() {
elements.scoreBoard.textContent = `得分: ${state.score}`;
// 更新最高分
if (state.score > state.highScore) {
state.highScore = state.score;
localStorage.setItem('snakeHighScore', state.highScore);
elements.highScoreBoard.textContent = `最高分: ${state.highScore}`;
}
}
// 游戏结束
function gameOver() {
clearInterval(state.gameInterval);
state.isGameOver = true;
// 显示最终得分
elements.finalScore.textContent = `最终得分: ${state.score}`;
elements.gameOver.classList.add('show');
}
// 事件监听
function setupEventListeners() {
// 键盘控制
document.addEventListener('keydown', e => {
if (state.isGameOver) return;
switch (e.key) {
case 'ArrowUp':
if (state.direction !== 'down') state.nextDirection = 'up';
break;
case 'ArrowDown':
if (state.direction !== 'up') state.nextDirection = 'down';
break;
case 'ArrowLeft':
if (state.direction !== 'right') state.nextDirection = 'left';
break;
case 'ArrowRight':
if (state.direction !== 'left') state.nextDirection = 'right';
break;
}
});
// 按钮控制
elements.upButton.addEventListener('click', () => {
if (state.direction !== 'down') state.nextDirection = 'up';
});
elements.leftButton.addEventListener('click', () => {
if (state.direction !== 'right') state.nextDirection = 'left';
});
elements.downButton.addEventListener('click', () => {
if (state.direction !== 'up') state.nextDirection = 'down';
});
elements.rightButton.addEventListener('click', () => {
if (state.direction !== 'left') state.nextDirection = 'right';
});
// 难度选择
elements.difficultySelect.addEventListener('change', e => {
const speed = parseInt(e.target.value);
state.difficulty =
speed === config.speeds.easy ? 'easy' :
speed === config.speeds.medium ? 'medium' :
speed === config.speeds.hard ? 'hard' : 'hell';
if (state.gameInterval) {
clearInterval(state.gameInterval);
startGameLoop();
}
});
// 重新开始按钮
elements.restartButton.addEventListener('click', initGame);
elements.restartButtonModal.addEventListener('click', initGame);
// 触摸控制(移动设备)
let touchStartX = 0;
let touchStartY = 0;
elements.gameBoard.addEventListener('touchstart', e => {
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
}, {passive: false});
elements.gameBoard.addEventListener('touchmove', e => {
if (!touchStartX || !touchStartY || state.isGameOver) return;
const touchEndX = e.touches[0].clientX;
const touchEndY = e.touches[0].clientY;
const dx = touchEndX - touchStartX;
const dy = touchEndY - touchStartY;
if (Math.abs(dx) > Math.abs(dy)) {
// 水平滑动
if (dx > 0 && state.direction !== 'left') {
state.nextDirection = 'right';
} else if (dx < 0 && state.direction !== 'right') {
state.nextDirection = 'left';
}
} else {
// 垂直滑动
if (dy > 0 && state.direction !== 'up') {
state.nextDirection = 'down';
} else if (dy < 0 && state.direction !== 'down') {
state.nextDirection = 'up';
}
}
touchStartX = 0;
touchStartY = 0;
e.preventDefault();
}, {passive: false});
}
// 初始化游戏
setupEventListeners();
initGame();
</script>
</body>
</html>
有四种模式哦,上下左右可以控制蛇的前进方向