科学教育
标题:
帮我生成一个贪吃蛇代码
[打印本页]
作者:
张子硕
时间:
2025-9-30 14:24
标题:
帮我生成一个贪吃蛇代码
帮我生成一个贪吃蛇代码
作者:
kaia
时间:
2025-9-30 14:24
当然可以!贪吃蛇是一个经典的游戏,让我们一起来编写一个简单的贪吃蛇游戏代码吧。在这个代码中,我们会使用Python语言进行编写。
首先,我们需要安装一个叫做`pygame`的库,它可以帮助我们创建游戏窗口和处理游戏事件。你可以在命令行中输入以下命令来安装`pygame`库:
pip install pygame
复制代码
接下来,让我们开始编写贪吃蛇游戏的代码:
import pygame
import time
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇游戏')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义蛇和食物的大小
snake_block = 10
snake_speed = 15
# 设置字体
font_style = pygame.font.SysFont(None, 50)
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(window, black, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
window.blit(mesg, [window_width / 6, window_height / 3])
def gameLoop():
game_over = False
game_close = False
# 蛇的初始位置
x1 = window_width / 2
y1 = window_height / 2
# 蛇的初始移动方向
x1_change = 0
y1_change = 0
# 初始蛇身长度
snake_list = []
length_of_snake = 1
# 食物初始位置
foodx = round(random.randrange(0, window_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_close == True:
window.fill(white)
message("你失败了!按Q-退出或C-重新开始", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
window.fill(white)
pygame.draw.rect(window, green, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_list.append(snake_Head)
if len(snake_list) > length_of_snake:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_Head:
game_close = True
our_snake(snake_block, snake_list)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block) / 10.0) * 10.0
length_of_snake += 1
time.sleep(1 / snake_speed)
pygame.quit()
quit()
gameLoop()
复制代码
在这个简单的贪吃蛇游戏里,你可以通过键盘的方向键来控制小蛇的移动,吃到食物会让蛇变长。当蛇撞墙或者撞到自己时,游戏结束。希望你喜欢这个贪吃蛇游戏!如果有任何问题,欢迎随时问我。
作者:
张子硕
时间:
2025-9-30 14:36
生成html型的
作者:
kaia
时间:
2025-9-30 14:36
张子硕 发表于 2025-09-30 14:36
生成html型的
当然,现在让我们一起来创建一个简单的HTML版本的贪吃蛇游戏。在这个版本中,我们将使用HTML、CSS和JavaScript来实现。以下是一个基本的贪吃蛇游戏的HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇游戏</title>
<style>
#game-board {
width: 400px;
height: 400px;
border: 2px solid black;
position: relative;
}
.snake {
width: 10px;
height: 10px;
background-color: black;
position: absolute;
}
.food {
width: 10px;
height: 10px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="game-board">
</div>
<script>
// 初始化游戏相关变量
let board = document.getElementById('game-board');
let snake = [{x: 200, y: 200}];
let food = {x: 0, y: 0};
let direction = 'right';
let gameSpeed = 100;
// 创建初始食物
function createFood() {
food.x = Math.floor(Math.random() * 40) * 10;
food.y = Math.floor(Math.random() * 40) * 10;
let foodElement = document.createElement('div');
foodElement.className = 'food';
foodElement.style.left = food.x + 'px';
foodElement.style.top = food.y + 'px';
board.appendChild(foodElement);
}
// 移动蛇的位置
function moveSnake() {
let head = {x: snake[0].x, y: snake[0].y};
// 根据方向更新蛇头位置
if (direction === 'up') head.y -= 10;
else if (direction === 'down') head.y += 10;
else if (direction === 'left') head.x -= 10;
else if (direction === 'right') head.x += 10;
// 移除尾部并插入新蛇头
snake.pop();
snake.unshift(head);
}
// 渲染蛇和食物
function render() {
// 清空游戏面板
board.innerHTML = '';
// 渲染蛇
snake.forEach(segment => {
let segmentElement = document.createElement('div');
segmentElement.className = 'snake';
segmentElement.style.left = segment.x + 'px';
segmentElement.style.top = segment.y + 'px';
board.appendChild(segmentElement);
});
// 渲染食物
let foodElement = document.createElement('div');
foodElement.className = 'food';
foodElement.style.left = food.x + 'px';
foodElement.style.top = food.y + 'px';
board.appendChild(foodElement);
}
// 启动游戏
function startGame() {
createFood();
setInterval(() => {
moveSnake();
render();
}, gameSpeed);
}
document.addEventListener('keydown', event => {
if (event.key === 'ArrowUp' && direction !== 'down') direction = 'up';
else if (event.key === 'ArrowDown' && direction !== 'up') direction = 'down';
else if (event.key === 'ArrowLeft' && direction !== 'right') direction = 'left';
else if (event.key === 'ArrowRight' && direction !== 'left') direction = 'right';
});
startGame();
</script>
</body>
</html>
复制代码
这段代码会在网页上呈现一个简单的贪吃蛇游戏。你可以通过方向键来控制蛇的移动,吃到红色的食物后蛇会变长。希望这个例子对你有所帮助,如果有任何问题或者需要进一步解释,请随时告诉我。
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2