python小游戏贪吃蛇
时间: 2024-12-28 18:20:16 浏览: 1
### 使用 Python 制作贪吃蛇游戏
#### 游戏框架的选择
对于初学者来说,`turtle` 库是一个不错的选择来实现简单图形界面的游戏[^3];而对于更复杂的需求,则可以考虑 `pygame` 这样的专用游戏开发库[^4]。
#### Pygame 版本的贪吃蛇代码结构
下面展示了一个基于 `pygame` 的简化版贪吃蛇游戏的核心逻辑:
```python
import pygame
import time
import random
# 初始化 Pygame
pygame.init()
# 设置窗口大小
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Snake Game')
# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
# 蛇的位置初始化
snake_block_size = 10
snake_speed = 15
snake_list = []
length_of_snake = 1
x_change = 0
y_change = 0
x1 = width / 2
y1 = height / 2
# 食物位置随机生成
foodx = round(random.randrange(0, width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block_size) / 10.0) * 10.0
clock = pygame.time.Clock()
font_style = pygame.font.SysFont(None, 50)
def our_snake(snake_block, snake_List):
for x in snake_List:
pygame.draw.rect(screen, black, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [width / 6, height / 3])
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -snake_block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = snake_block_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -snake_block_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = snake_block_size
x_change = 0
# 边界碰撞检测
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_over = True
x1 += x_change
y1 += y_change
screen.fill(white)
# 绘制食物
pygame.draw.rect(screen, red, [foodx, foody, snake_block_size, snake_block_size])
# 更新蛇的身体部分
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 segment in snake_list[:-1]:
if segment == snake_head:
game_over = True
our_snake(snake_block_size, snake_list)
pygame.display.update()
# 吃到食物后的处理
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block_size) / 10.0) * 10.0
length_of_snake += 1
clock.tick(snake_speed)
message("You lost", red)
pygame.display.update()
time.sleep(2)
pygame.quit()
quit()
```
这段代码展示了如何利用 `pygame` 创建一个基本的贪吃蛇游戏循环,包括方向控制、边界和自我碰撞判断以及吃到食物后增长长度等功能[^2]。
阅读全文