用Python代码写贪吃蛇
时间: 2023-11-21 09:03:03 浏览: 64
抱歉,作为AI语言模型,我不具备编写代码的能力。但是,我可以提供一些Python贪吃蛇游戏的代码示例,您可以在此基础上进行修改和完善。
示例代码:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 定义游戏界面大小
screen_width = 800
screen_height = 600
# 创建游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色变量
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇的初始位置和大小
snake_block_size = 10
snake_list = []
snake_length = 1
# 定义食物的初始位置和大小
food_block_size = 10
food_x = round(random.randrange(0, screen_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - food_block_size) / 10.0) * 10.0
# 定义蛇的移动速度
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义游戏结束的函数
def game_over():
font_style = pygame.font.SysFont(None, 50)
message = font_style.render("Game Over", True, red)
screen.blit(message, [screen_width / 2 - 100, screen_height / 2 - 50])
pygame.display.update()
pygame.time.delay(2000)
# 定义蛇的移动函数
def move_snake(snake_list):
for x in snake_list:
pygame.draw.rect(screen, black, [x[0], x[1], snake_block_size, snake_block_size])
# 定义游戏循环
def game_loop():
# 定义全局变量
global food_x, food_y, snake_length, snake_list, snake_speed
# 定义蛇的初始位置和方向
snake_x = screen_width / 2
snake_y = screen_height / 2
snake_x_change = 0
snake_y_change = 0
# 定义游戏是否结束的变量
game_over = False
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
# 接收到退出事件后退出程序
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_x_change = -snake_block_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = snake_block_size
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -snake_block_size
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = snake_block_size
snake_x_change = 0
# 判断蛇是否撞到边界
if snake_x >= screen_width or snake_x < 0 or snake_y >= screen_height or snake_y < 0:
game_over()
# 移动蛇
snake_x += snake_x_change
snake_y += snake_y_change
# 清除屏幕
screen.fill(white)
# 画食物
pygame.draw.rect(screen, red, [food_x, food_y, food_block_size, food_block_size])
# 画蛇
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_over()
move_snake(snake_list)
pygame.display.update()
# 判断蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, screen_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - food_block_size) / 10.0) * 10.0
snake_length += 1
snake_speed += 1
# 控制蛇的移动速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出pygame
pygame.quit()
# 启动游戏循环
game_loop()
```
阅读全文