请帮我写一个贪吃蛇程序用Python语言
时间: 2023-11-30 14:04:18 浏览: 75
好的,以下是一个简单的贪吃蛇程序的Python代码,希望能帮到你:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置屏幕大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置标题
pygame.display.set_caption("贪吃蛇")
# 设置字体
font = pygame.font.SysFont(None, 25)
# 定义蛇的初始位置和大小
SNAKE_SIZE = 10
SNAKE_X = SCREEN_WIDTH / 2
SNAKE_Y = SCREEN_HEIGHT / 2
snake = [[SNAKE_X, SNAKE_Y]]
direction = "right"
# 定义食物
FOOD_SIZE = 10
food = [random.randint(0, SCREEN_WIDTH - FOOD_SIZE),
random.randint(0, SCREEN_HEIGHT - FOOD_SIZE)]
# 定义游戏循环标志
done = False
# 定义游戏时钟
clock = pygame.time.Clock()
# 定义分数
score = 0
# 画蛇函数
def draw_snake(snake_list):
for x, y in snake_list:
pygame.draw.rect(screen, GREEN, [x, y, SNAKE_SIZE, SNAKE_SIZE])
# 画食物函数
def draw_food(food_list):
pygame.draw.rect(screen, RED, [food_list[0], food_list[1], FOOD_SIZE, FOOD_SIZE])
# 显示分数函数
def show_score(score):
score_text = font.render("Score: " + str(score), True, WHITE)
screen.blit(score_text, [0, 0])
# 游戏循环
while not done:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction = "left"
elif event.key == pygame.K_RIGHT:
direction = "right"
elif event.key == pygame.K_UP:
direction = "up"
elif event.key == pygame.K_DOWN:
direction = "down"
# 移动蛇
if direction == "right":
SNAKE_X += SNAKE_SIZE
elif direction == "left":
SNAKE_X -= SNAKE_SIZE
elif direction == "up":
SNAKE_Y -= SNAKE_SIZE
elif direction == "down":
SNAKE_Y += SNAKE_SIZE
# 判断是否吃到食物
if SNAKE_X == food[0] and SNAKE_Y == food[1]:
food = [random.randint(0, SCREEN_WIDTH - FOOD_SIZE),
random.randint(0, SCREEN_HEIGHT - FOOD_SIZE)]
snake.append([SNAKE_X, SNAKE_Y])
score += 10
# 删除蛇尾
if len(snake) > 1:
del snake[0]
# 判断游戏是否结束
if SNAKE_X < 0 or SNAKE_X >= SCREEN_WIDTH or SNAKE_Y < 0 or SNAKE_Y >= SCREEN_HEIGHT:
done = True
for i in range(1, len(snake)):
if SNAKE_X == snake[i][0] and SNAKE_Y == snake[i][1]:
done = True
# 清屏
screen.fill(BLACK)
# 画蛇和食物
draw_snake(snake)
draw_food(food)
# 显示分数
show_score(score)
# 刷新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(10)
# 退出pygame
pygame.quit()
```
这个程序使用Pygame库实现了一个简单的贪吃蛇游戏,你可以根据自己的需要对其进行修改和扩展。
阅读全文