请写出Python制作贪吃蛇游戏的代码
时间: 2023-03-07 18:15:11 浏览: 145
python制作的贪吃蛇小游戏程序+代码
这是一个使用Python制作贪吃蛇游戏的示例代码:import pygame
import sys
import random
import time# 初始化pygame
pygame.init()# 设置窗口
width = 500
height = 500
screen = pygame.display.set_mode((width, height))# 设置标题
pygame.display.set_caption("贪吃蛇")# 设置游戏参数
block_size = 10
size = width // block_size
FPS = 10# 设置颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)# 初始化蛇
snake = [[3, 2], [3, 1], [3, 0]]# 初始化食物
food = [random.randint(0, size - 1), random.randint(0, size - 1)]# 初始化方向
direction = 'up'# 画方块
def draw_block(color, position):
x, y = position
pygame.draw.rect(screen, color, (x * block_size, y * block_size, block_size, block_size))# 游戏循环
while True:
# 监听事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
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[0][1] -= 1
elif direction == 'down':
snake[0][1] += 1
elif direction == 'left':
snake[0][0] -= 1
elif direction == 'right':
snake[0][0] += 1
# 移动蛇
for i in range(len(snake) - 1, 0, -1):
snake[i][0] = snake[i-1][0]
snake[i][1] = snake[i-1][1]
# 把食物放到屏幕上
if snake[0] == food:
food = [random.randint(0, size - 1), random.randint(0, size - 1)]
snake.append([snake[-1][0], snake[-1][1]])
# 填充屏幕
screen.fill(black)
# 画蛇
for block in snake:
draw_block(white, block)
# 画食物
draw_block(red, food)
# 更新画面
pygame.display.update()
# 控制游戏速度
time.sleep(1 / FPS)
阅读全文