import pygame, sys, random
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Python贪吃蛇")
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 蛇和食物初始化
snake = [[100, 50], [90, 50], [80, 50]] # 初始蛇身坐标
food = [random.randrange(1, (WIDTH//10)) * 10,
random.randrange(1, (HEIGHT//10)) * 10] # 食物随机生成[3](https://blog.csdn.net/DonQuixote_/article/details/81748231)
direction = 'RIGHT' # 初始移动方向
score = 0
clock = pygame.time.Clock()
while True:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 方向键控制[6](https://blog.csdn.net/Pythoncxy/article/details/93878915)
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'
# 蛇头移动
head = snake[0].copy()
if direction == 'UP': head[1] -= 10
elif direction == 'DOWN': head[1] += 10
elif direction == 'LEFT': head[0] -= 10
elif direction == 'RIGHT': head[0] += 10
snake.insert(0, head)
# 吃食物判断[2](https://blog.csdn.net/weixin_39938331/article/details/111416632)
if head == food:
score += 10
food = [random.randrange(1, (WIDTH//10)) * 10,
random.randrange(1, (HEIGHT//10)) * 10]
else:
snake.pop()
# 碰撞检测[5](https://blog.csdn.net/kj7762/article/details/122308159)
if (head[0] < 0 or head[0] >= WIDTH or
head[1] < 0 or head[1] >= HEIGHT or
head in snake[1:]):
print("Game Over! Score:", score)
pygame.quit()
sys.exit()
# 画面渲染
screen.fill(BLACK)
for pos in snake: # 绘制蛇身
pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, RED, pygame.Rect(food[0], food[1], 10, 10)) # 绘制食物
# 显示分数[7](https://blog.csdn.net/dengfaheng/article/details/81283041)
font = pygame.font.SysFont('arial', 20)
text = font.render(f'Score: {score}', True, WHITE)
screen.blit(text, (10, 10))
pygame.display.update()
clock.tick(10) # 控制游戏速度
special_food = {
'type': random.choice(['speed_up', 'slow_down']),
'position': [random.randrange(1, (WIDTH//10)) * 10,
random.randrange(1, (HEIGHT//10)) * 10]
}
import pickle
with open('score.dat', 'wb') as f:
pickle.dump(high_score, f)
while food in snake:
food = [random.randrange(1, (WIDTH//10)) * 10,
random.randrange(1, (HEIGHT//10)) * 10]
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)