import pygame
import sys
import random
# 初始化pygame
pygame.init()
# 设置窗口大小和标题
screen_width =800
screen_height =600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪食蛇游戏")
# 设置颜色
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)# 蛇的颜色
red = (255,0,0)# 食物的颜色
# 设置游戏参数
snake_speed =10 # 蛇的移动速度
snake_length =3 # 蛇的初始长度
food_spawn_rate =5 # 食物生成频率
# 蛇的初始位置
x = screen_width //2
y = screen_height //2
change_x =0
change_y =0
direction ='RIGHT'
# 食物的初始位置
foodx = random.randrange(10, screen_width -10,10)
foody = random.randrange(10, screen_height -10,10)
# 蛇的身体列表
snake_body = []
for iin range(snake_length):
snake_body.append([x - (i *10), y])
# 创建时钟对象来控制游戏帧率
clock = pygame.time.Clock()
fps =7 # 设置较低的帧率以减慢游戏速度
# 游戏主循环
running =True
while running:
for eventin pygame.event.get():
if event.type == pygame.QUIT:
running =False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction ='LEFT'
elif event.key == pygame.K_RIGHT:
direction ='RIGHT'
elif event.key == pygame.K_UP:
direction ='UP'
elif event.key == pygame.K_DOWN:
direction ='DOWN'
# 更新蛇的位置
if direction =='RIGHT':
change_x =10
change_y =0
elif direction =='LEFT':
change_x = -10
change_y =0
elif direction =='UP':
change_x =0
change_y = -10
elif direction =='DOWN':
change_x =0
change_y =10
x += change_x
y += change_y
# 检查蛇是否出边界
if x >= screen_widthor x <0 or y >= screen_heightor y <0:
print("Game Over!")
running =False
# 检查蛇是否吃到食物
if snake_body[0][0] == foodxand snake_body[0][1] == foody:
food_spawn_rate -=1 # 增加食物生成的难度
foodx = random.randrange(10, screen_width -10,10)
foody = random.randrange(10, screen_height -10,10)
snake_length +=1 # 蛇增长
# 蛇的身体增长逻辑
snake_body.insert(0, [x, y])
if len(snake_body) > snake_length:
snake_body.pop()
# 绘制背景
screen.fill(black)
# 绘制食物
pygame.draw.rect(screen, red, [foodx, foody,10,10])
# 绘制蛇的身体
for posin snake_body:
pygame.draw.rect(screen, green, [pos[0], pos[1],10,10])
# 更新屏幕显示
pygame.display.flip()
# 控制游戏帧率
clock.tick(fps)
# 食物生成逻辑
if food_spawn_rate ==0:
foodx = random.randrange(10, screen_width -10,10)
foody = random.randrange(10, screen_height -10,10)
food_spawn_rate =5 # 重置食物生成频率
# 退出游戏
pygame.quit()
sys.exit()
网友评论