设计一段python的贪吃蛇代码,要求有一个交互界面选择三种不同大小的边框和三种不同的速度,同时食物有三种不同的大小,可以记录并展示最高分
时间: 2024-05-07 15:20:52 浏览: 23
以下是一个基本的 Python 贪吃蛇游戏代码,它包含了交互界面、三种不同大小的边框、三种不同的速度和三种不同大小的食物,并且可以记录并展示最高分:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏区域大小
border_sizes = {
'small': (400, 300),
'medium': (600, 450),
'large': (800, 600)
}
# 初始速度
speeds = {
'slow': 5,
'medium': 10,
'fast': 20
}
# 食物大小
food_sizes = {
'small': 10,
'medium': 20,
'large': 30
}
# 颜色定义
colors = {
'white': (255, 255, 255),
'black': (0, 0, 0),
'red': (255, 0, 0),
'green': (0, 255, 0),
'blue': (0, 0, 255)
}
# 游戏设置
border_size = border_sizes['medium']
speed = speeds['medium']
food_size = food_sizes['medium']
# 显示设置
screen = pygame.display.set_mode(border_size)
pygame.display.set_caption("贪吃蛇")
# 蛇和食物的初始位置
snake_position = [(border_size[0] / 2, border_size[1] / 2)]
food_position = (random.randint(0, border_size[0] - food_size),
random.randint(0, border_size[1] - food_size))
# 蛇的初始方向和长度
direction = 'right'
snake_length = 1
# 分数和最高分
score = 0
high_score = 0
# 游戏主循环
running = True
while running:
# 事件监听
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != 'down':
direction = 'up'
elif event.key == pygame.K_DOWN and direction != 'up':
direction = 'down'
elif event.key == pygame.K_LEFT and direction != 'right':
direction = 'left'
elif event.key == pygame.K_RIGHT and direction != 'left':
direction = 'right'
# 移动蛇
if direction == 'up':
snake_head = (snake_position[0][0], snake_position[0][1] - speed)
elif direction == 'down':
snake_head = (snake_position[0][0], snake_position[0][1] + speed)
elif direction == 'left':
snake_head = (snake_position[0][0] - speed, snake_position[0][1])
elif direction == 'right':
snake_head = (snake_position[0][0] + speed, snake_position[0][1])
snake_position.insert(0, snake_head)
# 判断是否吃到食物
if snake_head[0] < food_position[0] + food_size and \
snake_head[0] + speed > food_position[0] and \
snake_head[1] < food_position[1] + food_size and \
snake_head[1] + speed > food_position[1]:
food_position = (random.randint(0, border_size[0] - food_size),
random.randint(0, border_size[1] - food_size))
snake_length += 1
score += 10
# 更新最高分
if score > high_score:
high_score = score
# 删除尾部
if len(snake_position) > snake_length:
del snake_position[-1]
# 绘制游戏界面
screen.fill(colors['black'])
# 绘制蛇
for position in snake_position:
pygame.draw.rect(screen, colors['green'], (position[0], position[1], speed, speed))
# 绘制食物
pygame.draw.rect(screen, colors['red'], (food_position[0], food_position[1], food_size, food_size))
# 绘制分数和最高分
score_font = pygame.font.Font(None, 36)
score_text = score_font.render("Score: " + str(score) + " High Score: " + str(high_score), True, colors['white'])
screen.blit(score_text, (10, 10))
pygame.display.update()
# 退出游戏
pygame.quit()
```
阅读全文