import pygame
import random
import sys
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen_width, screen_height = 640, 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇游戏")
# 设置颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
# 设置游戏参数
snake_block = 40
snake_speed = 10 # 增加游戏速度,以提高游戏体验
# 初始化蛇的位置
snake_list = [[50, 50], [40, 50], [30, 50]]
direction = 'RIGHT'
# 初始化食物位置
def generate_food_position():
return [random.randrange(0, screen_width // snake_block) * snake_block,
random.randrange(0, screen_height // snake_block) * snake_block]
food_position = generate_food_position()
food_spawn = True
# 分数
score = 0
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and direction != 'RIGHT':
direction = 'LEFT'
elif event.key == pygame.K_RIGHT and direction != 'LEFT':
direction = 'RIGHT'
elif event.key == pygame.K_UP and direction != 'DOWN':
direction = 'UP'
elif event.key == pygame.K_DOWN and direction != 'UP':
direction = 'DOWN'
# 更新蛇头位置
if direction == 'RIGHT':
snake_head = [snake_list[-1][0] + snake_block, snake_list[-1][1]]
elif direction == 'LEFT':
snake_head = [snake_list[-1][0] - snake_block, snake_list[-1][1]]
elif direction == 'UP':
snake_head = [snake_list[-1][0], snake_list[-1][1] - snake_block]
elif direction == 'DOWN':
snake_head = [snake_list[-1][0], snake_list[-1][1] + snake_block]
# 确保蛇头和食物的位置都是 snake_block 的倍数
snake_head[0] = (snake_head[0] // snake_block) * snake_block
snake_head[1] = (snake_head[1] // snake_block) * snake_block
# 检查是否撞到墙壁或自己
if (snake_head[0] < 0 or snake_head[0] >= screen_width or
snake_head[1] < 0 or snake_head[1] >= screen_height or
snake_head in snake_list):
running = False
# 检查是否吃到食物
if snake_head == food_position:
score += 1
food_spawn = False
else:
snake_list.pop(0)
snake_list.append(snake_head)
# 生成新食物
if not food_spawn:
food_position = generate_food_position()
food_spawn = True
# 绘制游戏画面
screen.fill(black)
# 绘制蛇
for segment in snake_list:
pygame.draw.rect(screen, white, [segment[0], segment[1], snake_block, snake_block])
# 绘制食物
pygame.draw.rect(screen, red, [food_position[0], food_position[1], snake_block, snake_block])
# 显示分数
font = pygame.font.SysFont(None, 36) # 使用默认字体
score_text = font.render(f"Score: {score}", True, white)
screen.blit(score_text, [10, 10])
pygame.display.update()
pygame.time.Clock().tick(snake_speed)
pygame.quit()