用python编段贪吃蛇代码
时间: 2023-07-23 18:42:13 浏览: 79
好的,这是一个简单的贪吃蛇游戏的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 = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始位置、大小和移动速度
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
snake_speed = [10, 0]
# 定义食物的初始位置和大小
food_pos = [random.randrange(1, (SCREEN_WIDTH//10)) * 10, random.randrange(1, (SCREEN_HEIGHT//10)) * 10]
food_size = [10, 10]
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义游戏结束函数
def game_over():
msg = font.render("游戏结束,按 Q 或任意键退出", True, RED)
msg_rect = msg.get_rect()
msg_rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
screen.blit(msg, msg_rect)
pygame.display.flip()
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_q:
pygame.quit()
sys.exit()
else:
return
# 游戏主循环
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_LEFT:
snake_speed = [-10, 0]
elif event.key == pygame.K_RIGHT:
snake_speed = [10, 0]
elif event.key == pygame.K_UP:
snake_speed = [0, -10]
elif event.key == pygame.K_DOWN:
snake_speed = [0, 10]
# 移动蛇的身体
for i in range(len(snake_body)-1, 0, -1):
snake_body[i] = list(snake_body[i-1])
snake_pos[0] += snake_speed[0]
snake_pos[1] += snake_speed[1]
snake_body[0] = list(snake_pos)
# 检查蛇是否吃到了食物
if snake_pos == food_pos:
food_pos = [random.randrange(1, (SCREEN_WIDTH//10)) * 10, random.randrange(1, (SCREEN_HEIGHT//10)) * 10]
snake_body.append([0, 0])
# 检查蛇是否撞到了墙或自己
if snake_pos[0] < 0 or snake_pos[0] > SCREEN_WIDTH-10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > SCREEN_HEIGHT-10:
game_over()
for block in snake_body[1:]:
if snake_pos == block:
game_over()
# 绘制游戏界面
screen.fill(BLACK)
for pos in snake_body:
pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, BLUE, pygame.Rect(food_pos[0], food_pos[1], food_size[0], food_size[1]))
pygame.display.update()
# 控制游戏速度
pygame.time.Clock().tick(20)
```
注意,该程序需要 Pygame 库的支持,如果你还没有安装 Pygame,请先安装它再运行程序。
阅读全文