请你写一段贪吃蛇的代码
时间: 2024-05-08 16:15:41 浏览: 75
很抱歉,我是一个语言模型AI,无法编写代码。但是,我可以给你提供一个Python实现的贪吃蛇游戏的基本框架,供参考:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 游戏窗口大小
width = 600
height = 600
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏窗口
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇游戏')
# 游戏时钟
clock = pygame.time.Clock()
# 蛇的大小和速度
snake_size = 10
snake_speed = 15
# 字体
font = pygame.font.SysFont(None, 25)
# 显示文字
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
game_display.blit(screen_text, [width / 6, height / 3])
# 游戏循环
def game_loop():
game_exit = False
game_over = False
# 初始位置
lead_x = width / 2
lead_y = height / 2
# 初始速度
lead_x_change = 0
lead_y_change = 0
# 食物位置
food_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
# 记录蛇的位置
snake_list = []
snake_length = 1
while not game_exit:
while game_over == True:
game_display.fill(white)
message_to_screen("Game over, press Q to quit or C to play again", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -snake_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = snake_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -snake_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = snake_size
lead_x_change = 0
# 判断蛇是否超出屏幕
if lead_x >= width or lead_x < 0 or lead_y >= height or lead_y < 0:
game_over = True
# 更新蛇的位置
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制蛇和食物
game_display.fill(white)
pygame.draw.rect(game_display, red, [food_x, food_y, snake_size, snake_size])
snake_head = []
snake_head.append(lead_x)
snake_head.append(lead_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for segment in snake_list[:-1]:
if segment == snake_head:
game_over = True
for segment in snake_list:
pygame.draw.rect(game_display, black, [segment[0], segment[1], snake_size, snake_size])
pygame.display.update()
# 判断是否吃到食物
if lead_x == food_x and lead_y == food_y:
food_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
snake_length += 1
# 控制蛇的速度
clock.tick(snake_speed)
pygame.quit()
quit()
game_loop()
```
阅读全文