话不多说,直接上代码
'''
Author: Zhao 2869210303@qq.com
Date: 2025-03-15 20:08:40
LastEditors: Zhao 2869210303@qq.com
LastEditTime: 2025-03-16 13:16:00
FilePath: \2024_2025_1\snake_game.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import pygame
import random
import sys
# 初始化pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 定义游戏窗口大小
WIDTH, HEIGHT = 600, 400
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义时钟
clock = pygame.time.Clock()
# 定义蛇的初始位置和速度-
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
snake_direction = 'RIGHT'
snake_speed = 15
# 定义食物的初始位置
food_pos = [random.randrange(1, WIDTH//10) * 10, random.randrange(1, HEIGHT//10) * 10]
food_spawn = True
# 游戏主循环
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_UP and snake_direction != 'DOWN':
snake_direction = 'UP'
elif event.key == pygame.K_DOWN and snake_direction != 'UP':
snake_direction = 'DOWN'
elif event.key == pygame.K_LEFT and snake_direction != 'RIGHT':
snake_direction = 'LEFT'
elif event.key == pygame.K_RIGHT and snake_direction != 'LEFT':
snake_direction = 'RIGHT'
# 移动蛇
if snake_direction == 'UP':
snake_pos[1] -= 10
elif snake_direction == 'DOWN':
snake_pos[1] += 10
elif snake_direction == 'LEFT':
snake_pos[0] -= 10
elif snake_direction == 'RIGHT':
snake_pos[0] += 10
# 蛇身更新
snake_body.insert(0, list(snake_pos))
if snake_pos == food_pos:
food_spawn = False
else:
snake_body.pop()
# 生成新食物
if not food_spawn:
food_pos = [random.randrange(1, WIDTH//10) * 10, random.randrange(1, HEIGHT//10) * 10]
food_spawn = True
snake_speed += 1 # 蛇的速度随着长度增加
# 绘制游戏界面
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, RED, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# 碰撞检测
if snake_pos[0] < 0 or snake_pos[0] > WIDTH-10:
break
if snake_pos[1] < 0 or snake_pos[1] > HEIGHT-10:
break
for block in snake_body[1:]:
if snake_pos == block:
break
# 更新显示
pygame.display.flip()
clock.tick(snake_speed)
再展示一下运行的效果截图: