写一python贪吃蛇的代码
时间: 2023-03-12 16:34:28 浏览: 180
# 贪吃蛇代码
import pygame
import random
# 定义颜色变量
red = pygame.Color(255, 0, 0) # 贪吃蛇头部的颜色
green = pygame.Color(0, 255, 0) # 贪吃蛇身体的颜色
black = pygame.Color(0, 0, 0) # 游戏窗口的背景色
white = pygame.Color(255, 255, 255) # 食物的颜色
# 定义游戏窗口的宽和高
width = 500
height = 500
# 定义贪吃蛇的移动速度
speed = 20
# 定义贪吃蛇的初始位置
snake_x = 250
snake_y = 250
# 定义贪吃蛇的初始长度
snake_size = 10
# 定义贪吃蛇的初始方向
snake_direction = 'right'
# 定义食物的位置
food_x = random.randint(0, width - snake_size)
food_y = random.randint(0, height - snake_size)
# 初始化pygame
pygame.init()
# 设置游戏窗口
window = pygame.display.set_mode((width, height))
# 设置游戏窗口的标题
pygame.display.set_caption('贪吃蛇小游戏')
# 定义游戏循环
game_over = False
while not game_over:
# 处理游戏的退出
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 处理键盘事件
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_direction != 'right':
snake_direction = 'left'
if event.key == pygame.K_RIGHT and snake_direction != 'left':
snake_direction = 'right'
if event.key == pygame.K_UP and snake_direction != 'down':
snake_direction = 'up'
if event.key == pygame.K_DOWN and snake_direction != 'up':
snake_direction = 'down'
# 根据贪吃蛇的方向,计算贪吃蛇的新位置
if snake_direction == 'left':
snake_x = snake_x - speed
if snake_direction == 'right':
snake_x = snake_x + speed
if snake_direction == 'up':
snake_y = snake_y - speed
if snake_direction == 'down':
snake_y = snake_y + speed
# 如果贪吃蛇的新位置超出边界,游戏结束
if snake_x < 0 or snake_x > width or snake_y < 0 or snake_y > height:
game_over = True
# 绘制游戏窗口的背景
window.fill(black)
# 绘制贪吃蛇的头部
pygame.draw.rect(window, red, (snake_x, snake_y, snake_size, snake_size))
# 绘制食物
pygame.draw.rect(window, white, (food_x, food_y, snake_size, snake_size))
# 刷新游戏窗口
pygame.display.update()
# 退出游戏
pygame.quit()
阅读全文