python编写贪吃蛇程序
时间: 2023-05-14 10:04:27 浏览: 98
好的,我可以回答这个问题。以下是一个简单的 Python 贪吃蛇程序的代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置屏幕大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始位置和大小
snake_block_size = 10
snake_speed = 15
x1 = SCREEN_WIDTH / 2
y1 = SCREEN_HEIGHT / 2
# 定义蛇的移动方向
x1_change = 0
y1_change = 0
# 定义食物的位置
foodx = round(random.randrange(0, SCREEN_WIDTH - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, SCREEN_HEIGHT - snake_block_size) / 10.0) * 10.0
# 定义蛇的长度
snake_List = []
Length_of_snake = 1
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义得分函数
def Your_score(score):
value = font_style.render("Your Score: " + str(score), True, WHITE)
screen.blit(value, [0, 0])
# 定义蛇的绘制函数
def our_snake(snake_block_size, snake_List):
for x in snake_List:
pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_block_size, snake_block_size])
# 开始游戏循环
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:
x1_change = -snake_block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
# 判断蛇是否碰到边界
if x1 >= SCREEN_WIDTH or x1 < 0 or y1 >= SCREEN_HEIGHT or y1 < 0:
game_over = True
# 移动蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制背景
screen.fill(BLACK)
# 绘制食物
pygame.draw.rect(screen, BLUE, [foodx, foody, snake_block_size, snake_block_size])
# 将蛇的位置添加到列表中
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
# 判断蛇是否吃到了食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, SCREEN_WIDTH - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, SCREEN_HEIGHT - snake_block_size) / 10.0) * 10.0
Length_of_snake += 1
# 判断蛇是否碰到了自己
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_over = True
# 绘制蛇
our_snake(snake_block_size, snake_List)
# 绘制得分
Your_score(Length_of_snake - 1)
# 更新屏幕
pygame.display.update()
# 控制蛇的速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出 Pygame
pygame.quit()
```
希望能对你有所帮助!
阅读全文